﻿using AutoMapper;
using Coldairarrow.Entity;
using Coldairarrow.Entity.AM;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.Entity.View;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_JobBookingBusiness : BaseBusiness<PB_JobBooking>, IPB_JobBookingBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IOperatorDept _opdept;
        readonly IMapper _mapper;
        readonly ICheckOperation _check;
        public PB_JobBookingBusiness(IDbAccessor db, IOperator @operator, IMapper mapper, IOperatorDept @opdept, ICheckOperation @check)
            : base(db)
        {
            _operator = @operator;
            _opdept = @opdept;
            _mapper = mapper;
            _check = @check;
        }

        #region 外部接口

        public async Task<PageResult<PB_JobBooking>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_JobBooking>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_JobBooking, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            q = q.Where(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PageResult<PB_JobBookingDTO>> GetWorkReportDataListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_ProductionOrder, PB_DesignList, PB_Project, PB_JobBookingDTO>> select = (a, b, c, d, e, f, g, h) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSpec = e.Spec,
                ProjectName = h.Name,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_ProductionOrder>() on b.ParentId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_DesignList>() on f.DesignId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    join h in Db.GetIQueryable<PB_Project>() on g.ProjectId equals h.Id into ah
                    from h in ah.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g, h);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.MaterialName, keyword));
            }
            q = q.Where(p => _operator.Property.DeptIds.Contains(p.DeptId));
            return await q.GetPageResultAsync(input);
        }

        public async Task<PageResult<PB_JobBookingDTO>> GetQualityDataListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_JobBookingDTO>> select = (a, b, c, d, e) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSpec = e.Spec,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.MaterialName, keyword));
            }
            q = q.Where(x => x.Status != 0);
            return await q.GetPageResultAsync(input);
        }

        public async Task<PB_JobBooking> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_JobBooking data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_JobBooking data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// PDA报工保存接口
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="_mongodbOptions">数据</param>
        /// <returns></returns>
        [Transactional]
        public async Task AddData(List<PB_JobBookingDTOquery> datainfo, MongoDBOptions _mongodbOptions)
        {
            List<PB_JobBooking> PB_JobBookingList = new List<PB_JobBooking>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            List<string> liststr = new List<string>();
            string sqlMain = string.Empty;
            foreach (var data in datainfo)
            {
                liststr.Add(data.Id);
                PB_JobBooking pB_Job = new PB_JobBooking();
                pB_Job.Id = data.Id;
                pB_Job.ParentId = data.ParentId;
                pB_Job.Nums = data.Nums;
                pB_Job.ReturnNums = data.ReturnNums;
                pB_Job.TreatmentType = data.TreatmentType;
                pB_Job.Reason = data.Reason;
                pB_Job.QualityUserId = data.QualityUserId;
                pB_Job.QualityUserName = data.QualityUserName;
                pB_Job.QualityTime = data.QualityTime;
                pB_Job.CreateTime = data.CreateTime;
                pB_Job.CreatorId = data.CreatorId;
                pB_Job.CreatorRealName = data.CreatorRealName;
                pB_Job.StatisticsUserId = data.StatisticsUserId;
                pB_Job.StatisticsUserName = data.StatisticsUserName;
                pB_Job.StatisticsTime = data.StatisticsTime;
                pB_Job.StatisticsNums = data.StatisticsNums;
                pB_Job.TakeOverUserId = data.TakeOverUserId;
                pB_Job.TakeOverUserName = data.TakeOverUserName;
                pB_Job.TakeOverTime = data.TakeOverTime;
                pB_Job.Status = 0;
                pB_Job.MaterialId = data.MaterialId;
                pB_Job.MaterialName = data.MaterialName;
                pB_Job.Deleted = data.Deleted;
                pB_Job.CreateTime = data.CreateTime;
                pB_Job.CreatorId = data.CreatorId;
                pB_Job.CreatorRealName = data.CreatorRealName;
                pB_Job.WorkshopId = data.WorkshopId;
                pB_Job.OldOrNew = data.IsRefurbishment;  //是翻新还是新制
                //解析用户二维码信息
                string[] usermodel = data.userqrcode.Split(',');
                //解析设备二维码信息
                string[] devicemodel = data.deviceqrcode.Split(',');
                pB_Job.DeptId = usermodel[2].ToString();
                pB_Job.ReportUserId = usermodel[1].ToString();
                pB_Job.ReportTime = DateTime.Now;
                pB_Job.DeviceId = devicemodel[3].ToString();
                pB_Job.Status = 0;  //状态：0=待质检；1=全部合格；2=有不合格
                pB_Job.ReportUserName = _operator?.Property?.RealName;
                PB_JobBookingList.Add(pB_Job);
                //操作明细插入mongo
                PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                pbdata.Id = IdHelper.GetId();
                pbdata.No = data.Id;
                pbdata.ParentId = data.ParentId;
                pbdata.Nums = data.Nums;
                pbdata.DeptId = usermodel[2].ToString();
                pbdata.DeviceId = devicemodel[3].ToString();
                pbdata.OperationUserId = usermodel[1].ToString();
                pbdata.OperationUserName = _operator?.Property?.RealName;
                pbdata.OperationTime = DateTime.Now;
                pbdata.Type = 0;
                pbdata.OldOrNew = data.IsRefurbishment; //是翻新还是新制
                pbdetailed.Add(pbdata);
                List<PB_JobBookingQrCode> listdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.OrderDetailId == data.ParentId && x.ParentId == null).ToListAsync();
                if (listdata.Count > 0)
                {
                    string detaileids = "";
                    foreach (var item in listdata)
                    {
                        detaileids += "'" + item.Id + "',";
                    }
                    detaileids = detaileids.Substring(0, detaileids.Length - 1);
                    sqlMain += @" update PB_JobBookingQrCode set ParentId='" + data.Id + "' where Id in (" + detaileids + "); ";
                }
            }
            if (!sqlMain.IsNullOrEmpty())
            {
                await Db.ExecuteSqlAsync(sqlMain);
            }
            //插入mongo报工日志
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            await Db.InsertAsync(PB_JobBookingList);
        }

        public async Task UpdataListData(List<PB_JobBookingListDTO> data, string userqrcode, MongoDBOptions _mongodbOptions)
        {
            //解析用户二维码信息
            string[] usermodel = userqrcode.Split(',');
            List<PB_JobBooking> addDetail = new List<PB_JobBooking>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            foreach (var item in data)
            {
                PB_JobBooking pbjb = new PB_JobBooking();
                pbjb.Id = item.Id;
                pbjb.ParentId = item.ParentId;
                pbjb.Nums = item.Nums;
                pbjb.ReturnNums = item.ReturnNums;
                pbjb.TreatmentType = item.TreatmentType;
                pbjb.Reason = item.Reason;
                pbjb.DeviceId = item.DeviceId;
                pbjb.DeptId = item.DeptId;
                pbjb.ReportUserId = item.ReportUserId;
                pbjb.ReportUserName = item.ReportUserName;
                pbjb.ReportTime = item.ReportTime;
                pbjb.QualityUserId = usermodel[1].ToString();
                pbjb.QualityUserName = _operator?.Property?.RealName;
                pbjb.QualityTime = DateTime.Now;
                pbjb.StatisticsUserId = item.StatisticsUserId;
                pbjb.StatisticsUserName = item.StatisticsUserName;
                pbjb.StatisticsTime = item.StatisticsTime;
                pbjb.StatisticsNums = item.StatisticsNums;
                pbjb.TakeOverUserId = usermodel[1].ToString();
                pbjb.TakeOverUserName = _operator?.Property?.RealName;
                pbjb.TakeOverTime = DateTime.Now;
                pbjb.CreateTime = item.CreateTime;
                pbjb.CreatorId = item.CreatorId;
                pbjb.CreatorRealName = item.CreatorRealName;
                pbjb.Status = 1; //状态：0=待质检；1=全部合格；2=有不合格
                pbjb.WorkshopId = item.WorkshopId;
                pbjb.MaterialId = item.MaterialId;
                pbjb.MaterialName = item.MaterialName;
                pbjb.OldOrNew = item.OldOrNew;
                addDetail.Add(pbjb);
                //操作明细插入mongo
                PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                pbdata.Id = IdHelper.GetId();
                pbdata.No = item.Id;
                pbdata.ParentId = item.ParentId;
                pbdata.Nums = item.ReturnNums;
                pbdata.DeptId = item.DeptId;
                pbdata.DeviceId = item.DeviceId;
                pbdata.OperationUserId = usermodel[1].ToString();
                pbdata.OperationUserName = _operator?.Property?.RealName;
                pbdata.OperationTime = DateTime.Now;
                pbdata.Type = 1;
                pbdata.OldOrNew = item.OldOrNew;
                pbdetailed.Add(pbdata);
            }
            //插入mongo质检日志
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            await Db.UpdateAsync(addDetail);
        }

        public async Task<List<PB_JobBookingDTO>> GetTheDataDeatil(string OrderDetailQrCode)
        {
            //解析任务单明细二维码
            string[] usermodel = OrderDetailQrCode.Split(',');
            string OrderDetailId = usermodel[2].ToString();
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingDTO>> select = (a, b, c, d, e, f, g) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSimpleName = e.SimpleName,
                MaterialSpec = e.Spec,
                MaterialTypeName = f.Name,
                DeptName = g.Name,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_MaterialType>() on e.MaterialTypeId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_Department>() on a.DeptId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            q = q.Where(w => w.ParentId == OrderDetailId && w.Status == 0);
            return await q.ToListAsync();
        }

        public async Task<List<PB_JobBookingDTO>> GetTheDataDeatilInput(string OrderDetailQrCode)
        {
            //解析任务单明细二维码
            string[] usermodel = OrderDetailQrCode.Split(',');
            string OrderDetailId = usermodel[1].ToString();
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingDTO>> select = (a, b, c, d, e, f, g) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSimpleName = e.SimpleName,
                MaterialSpec = e.Spec,
                MaterialTypeName = f.Name,
                DeptName = g.Name,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_MaterialType>() on e.MaterialTypeId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_Department>() on a.DeptId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            q = q.Where(w => w.ParentId == OrderDetailId && w.Status == 0);
            return await q.ToListAsync();
        }

        public async Task<Object> GetAnalyticCode(string QrCode)
        {
            if (!QrCode.IsNullOrEmpty())
            {
                string[] qrcodemodel = QrCode.Split(',');
                string juber = qrcodemodel[0].ToString();
                switch (juber)
                {
                    case "01":  //用户
                        var q = await Db.GetIQueryable<Base_User>().Where(x => x.Id == qrcodemodel[1].ToString() && x.EmployeStatus == false).FirstOrDefaultAsync();
                        if (q != null)
                        {
                            //生成token,有效期一天
                            JWTPayload jWTPayload = new JWTPayload
                            {
                                UserId = q.Id,
                                Expire = DateTime.Now.AddDays(1)
                            };
                            string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
                            Base_UserPDALogDTO buser = new Base_UserPDALogDTO();
                            buser.Id = q.Id;
                            buser.CreateTime = q.CreateTime;
                            buser.CreatorId = q.CreatorId;
                            buser.Deleted = q.Deleted;
                            buser.UserName = q.UserName;
                            buser.Password = q.Password;
                            buser.QrCode = q.QrCode;
                            buser.RealName = q.RealName;
                            buser.Sex = q.Sex;
                            buser.UserCode = q.UserCode;
                            buser.Birthday = q.Birthday;
                            buser.DepartmentId = q.DepartmentId;
                            buser.Token = token;

                            return buser;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的用户二维码信息");
                        }
                    case "03":  //生产任务单明细
                        string orderdetailId = "";
                        if (qrcodemodel.Length == 3)
                        {
                            orderdetailId = qrcodemodel?[2].ToString();
                        }
                        else
                        {
                            orderdetailId = qrcodemodel?[1].ToString();
                        }
                        var OrderDetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == orderdetailId).FirstOrDefaultAsync();
                        if (OrderDetaildata != null)
                        {
                            return OrderDetaildata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的任务单明细二维码信息");
                        }
                    case "11":  //设备
                        var Devicedata = await Db.GetIQueryable<Base_Device>().Where(x => x.Id == qrcodemodel[3].ToString()).FirstOrDefaultAsync();
                        if (Devicedata != null)
                        {
                            return Devicedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的设备二维码信息");
                        }
                    case "13": //包
                        var PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (PackListdata != null)
                        {
                            return PackListdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的包二维码信息");
                        }
                    case "06": //货位
                        var Locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Locationdata != null)
                        {
                            var areadata = await Db.GetIQueryable<PB_StorArea>().Where(x => x.Id == Locationdata.AreaId).FirstOrDefaultAsync();
                            var rackdata = await Db.GetIQueryable<PB_Rack>().Where(x => x.Id == Locationdata.RackId).FirstOrDefaultAsync();
                            Locationdata.Name = areadata.Name + "/" + rackdata.Name + "/" + Locationdata.Name;
                            return Locationdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的货位二维码信息");
                        }
                    case "21":   //备货单
                        var WarehousingNoticedata = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (WarehousingNoticedata != null)
                        {
                            return WarehousingNoticedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的备货单二维码信息");
                        }
                    case "23":   //收货单
                        Expression<Func<TD_Receiving, Base_EnumItem, ReceivingDTO>> select = (a, b) => new ReceivingDTO
                        {
                            ReceTypeName = b.Name
                        };
                        select = select.BuildExtendSelectExpre();
                        var receq = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                                    join b in Db.GetIQueryable<Base_EnumItem>() on a.Type equals b.Code into ab
                                    from b in ab.Where(u => u.EnumCode.Contains("ReceiveType")).DefaultIfEmpty()
                                    select @select.Invoke(a, b);
                        var Receivingdata = await receq.Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Receivingdata != null)
                        {
                            return Receivingdata;
                        }
                        else if (Receivingdata.Status == 5)
                        {
                            throw new BusException("收货单已作废!");
                        }
                        else if (Receivingdata.Status == 4)
                        {
                            throw new BusException("收货单已完成!");
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的收货单二维码信息");
                        }
                    case "25":   //调拨单
                        var Allocatedata = await Db.GetIQueryable<TD_Allocate>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 3).FirstOrDefaultAsync();
                        if (Allocatedata != null)
                        {
                            return Allocatedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的调拨单二维码信息");
                        }
                    case "04":   //物料
                        var materid = string.Empty;
                        if (qrcodemodel.Length > 2)
                        {
                            materid = qrcodemodel?[3].ToString();
                        }
                        else
                        {
                            materid = qrcodemodel?[1].ToString();
                        }
                        var Materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materid).FirstOrDefaultAsync();
                        if (Materialdata != null)
                        {
                            return Materialdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的物料二维码信息");
                        }
                    case "32":   //托盘
                        var Traydata = await Db.GetIQueryable<PB_Tray>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Traydata != null)
                        {
                            return Traydata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的托盘二维码信息");
                        }
                    case "02":   //生产任务单(翻新)
                        var Orderdata = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == qrcodemodel[1].ToString() && x.IsRefurbishment == 0).FirstOrDefaultAsync();
                        if (Orderdata != null)
                        {
                            return Orderdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的生产任务单二维码信息");
                        }
                    case "29":   //外协任务单
                        var OutsourcingBilldata = await Db.GetIQueryable<PB_OutsourcingBill>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 1).FirstOrDefaultAsync();
                        if (OutsourcingBilldata != null)
                        {
                            return OutsourcingBilldata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的外协任务单二维码信息");
                        }
                    case "28":   //盘点单
                        var CheckData = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 2).FirstOrDefaultAsync();
                        if (CheckData != null)
                        {
                            return CheckData;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的盘点单二维码信息");
                        }
                    case "16":   //派工单明细
                        var DispatchData = await Db.GetIQueryable<PB_DispatchDetail>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (DispatchData != null)
                        {
                            return DispatchData;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的派工单二维码信息");
                        }
                    case "41":   //资产盘点单
                        Expression<Func<AM_AssetCheck, Base_Department, AM_AssetCheckDTO>> AM_select = (a, b) => new AM_AssetCheckDTO
                        {
                            DeptName = b.Name
                        };
                        AM_select = AM_select.BuildExtendSelectExpre();
                        var AM_q = from a in Db.GetIQueryable<AM_AssetCheck>().AsExpandable()
                                   join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   select @AM_select.Invoke(a, b);
                        var AssetCheck = await AM_q.Where(x => x.CheckId == Convert.ToInt32(qrcodemodel[1]) && x.Status < 2).FirstOrDefaultAsync();
                        if (AssetCheck != null)
                        {
                            return AssetCheck;
                        }
                        else
                        {
                            throw new BusException("请扫描正确的资产盘点单二维码信息或检查盘点单是否已开始盘点");
                        }
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }

        public async Task<Object> GetAnalyticInputCode(string QrCode)
        {
            if (!QrCode.IsNullOrEmpty())
            {
                string[] qrcodemodel = QrCode.Split(',');
                string juber = qrcodemodel[0].ToString();
                switch (juber)
                {
                    case "01":  //用户
                        var q = await Db.GetIQueryable<Base_User>().Where(x => x.UserCode == qrcodemodel[1].ToString() && x.EmployeStatus == false).FirstOrDefaultAsync();
                        if (q != null)
                        {
                            //生成token,有效期一天
                            JWTPayload jWTPayload = new JWTPayload
                            {
                                UserId = q.Id,
                                Expire = DateTime.Now.AddDays(1)
                            };
                            string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
                            Base_UserPDALogDTO buser = new Base_UserPDALogDTO();
                            buser.Id = q.Id;
                            buser.CreateTime = q.CreateTime;
                            buser.CreatorId = q.CreatorId;
                            buser.Deleted = q.Deleted;
                            buser.UserName = q.UserName;
                            buser.Password = q.Password;
                            buser.QrCode = q.QrCode;
                            buser.RealName = q.RealName;
                            buser.Sex = q.Sex;
                            buser.UserCode = q.UserCode;
                            buser.Birthday = q.Birthday;
                            buser.DepartmentId = q.DepartmentId;
                            buser.Token = token;

                            return buser;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的用户信息");
                        }
                    case "03":  //生产任务单明细
                        string orderdetailId = "";
                        if (qrcodemodel.Length == 3)
                        {
                            orderdetailId = qrcodemodel?[2].ToString();
                        }
                        else
                        {
                            orderdetailId = qrcodemodel?[1].ToString();
                        }
                        var OrderDetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == orderdetailId).FirstOrDefaultAsync();
                        if (OrderDetaildata != null)
                        {
                            return OrderDetaildata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的任务单明细信息");
                        }
                    case "11":  //设备
                        var Devicedata = await Db.GetIQueryable<Base_Device>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Devicedata != null)
                        {
                            return Devicedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的设备信息");
                        }
                    case "13":  //打包（包key）
                        var PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (PackListdata != null)
                        {
                            return PackListdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的包信息");
                        }
                    case "06":  //货位key值
                        var Locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Locationdata != null)
                        {
                            var areadata = await Db.GetIQueryable<PB_StorArea>().Where(x => x.Id == Locationdata.AreaId).FirstOrDefaultAsync();
                            var rackdata = await Db.GetIQueryable<PB_Rack>().Where(x => x.Id == Locationdata.RackId).FirstOrDefaultAsync();
                            Locationdata.Name = areadata.Name + "/" + rackdata.Name + "/" + Locationdata.Name;
                            return Locationdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的货位信息");
                        }
                    case "21":   //备货单
                        var WarehousingNoticedata = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (WarehousingNoticedata != null)
                        {
                            return WarehousingNoticedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的备货单信息");
                        }
                    case "23":   //收货单
                        Expression<Func<TD_Receiving, Base_EnumItem, ReceivingDTO>> select = (a, b) => new ReceivingDTO
                        {
                            ReceTypeName = b.Name
                        };
                        select = select.BuildExtendSelectExpre();
                        var receq = from a in Db.GetIQueryable<TD_Receiving>().AsExpandable()
                                    join b in Db.GetIQueryable<Base_EnumItem>() on a.Type equals b.Code into ab
                                    from b in ab.Where(u => u.EnumCode.Contains("ReceiveType")).DefaultIfEmpty()
                                    select @select.Invoke(a, b);
                        var Receivingdata = await receq.Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Receivingdata != null)
                        {
                            return Receivingdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的收货单二维码信息");
                        }
                    case "25":   //调拨单
                        var Allocatedata = await Db.GetIQueryable<TD_Allocate>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 3).FirstOrDefaultAsync();
                        if (Allocatedata != null)
                        {
                            return Allocatedata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的调拨单二维码信息");
                        }
                    case "04":   //物料
                        var Materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Materialdata != null)
                        {
                            return Materialdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的物料二维码信息");
                        }
                    case "32":   //托盘
                        var Traydata = await Db.GetIQueryable<PB_Tray>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (Traydata != null)
                        {
                            return Traydata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的托盘二维码信息");
                        }
                    case "02":   //生产任务单(翻新)
                        var Orderdata = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == qrcodemodel[1].ToString() && x.IsRefurbishment == 0).FirstOrDefaultAsync();
                        if (Orderdata != null)
                        {
                            return Orderdata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的生产任务单二维码信息");
                        }
                    case "29":   //外协任务单
                        var OutsourcingBilldata = await Db.GetIQueryable<PB_OutsourcingBill>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 1).FirstOrDefaultAsync();
                        if (OutsourcingBilldata != null)
                        {
                            return OutsourcingBilldata;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的外协任务单二维码信息");
                        }
                    case "28":   //盘点单
                        var CheckData = await Db.GetIQueryable<TD_Check>().Where(x => x.Id == qrcodemodel[1].ToString() && x.Status == 2).FirstOrDefaultAsync();
                        if (CheckData != null)
                        {
                            return CheckData;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的盘点单单二维码信息");
                        }
                    case "16":   //派工单明细
                        var DispatchData = await Db.GetIQueryable<PB_DispatchDetail>().Where(x => x.Id == qrcodemodel[1].ToString()).FirstOrDefaultAsync();
                        if (DispatchData != null)
                        {
                            return DispatchData;
                        }
                        else
                        {
                            throw new BusException("请扫描或输入正确的派工单二维码信息");
                        }
                    case "41":   //资产盘点单
                        Expression<Func<AM_AssetCheck, Base_Department, AM_AssetCheckDTO>> AM_select = (a, b) => new AM_AssetCheckDTO
                        {
                            DeptName = b.Name
                        };
                        AM_select = AM_select.BuildExtendSelectExpre();
                        var AM_q = from a in Db.GetIQueryable<AM_AssetCheck>().AsExpandable()
                                   join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   select @AM_select.Invoke(a, b);
                        var AssetCheck = await AM_q.Where(x => x.CheckId == Convert.ToInt32(qrcodemodel[1]) && x.Status < 2).FirstOrDefaultAsync();
                        if (AssetCheck != null)
                        {
                            return AssetCheck;
                        }
                        else
                        {
                            throw new BusException("请扫描正确的资产盘点单二维码信息或检查盘点单是否已开始盘点");
                        }
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取全局变量
        /// </summary>
        /// <param name="LinkType">全局变量码</param>
        /// <returns></returns>
        public async Task<Object> GetLinkTypeDataAsync(string LinkType)
        {
            Base_LinkType linktypedata = await _opdept.GetLinkType(LinkType);
            return linktypedata;
        }

        public async Task<Object> GetQueueListAsync(string servicecode, MongoDBOptions _mongodbOptions)
        {
            if (!servicecode.IsNullOrEmpty())
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                int i = 0;
                switch (servicecode)
                {
                    case "01":  //用户
                        var user = await Db.GetIQueryable<Base_User>().ToListAsync();

                        foreach (var item in user)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = i.ToString();
                            pq.QrCode = item.QrCode;
                            pq.Name = item.RealName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "用户";
                            pq.Type = Skill_Type.user.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return user.Count();
                    case "11":
                        var device = await Db.GetIQueryable<Base_Device>().ToListAsync();
                        foreach (var item in device)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = i.ToString();
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "设备";
                            pq.Type = Skill_Type.equipment.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return device.Count();
                    case "06":
                        var location = await Db.GetIQueryable<PB_Location>().ToListAsync();
                        foreach (var item in location)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = i.ToString();
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "货位";
                            pq.Type = Skill_Type.Location.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return location.Count();
                    //case "23":
                    //    PB_Material pbma = await Db.GetIQueryable<PB_Material>().FirstOrDefaultAsync();
                    //    Base_Department bdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == pbma.DeptId).FirstOrDefaultAsync();
                    //    PB_MaterialType tydata = await Db.GetIQueryable<PB_MaterialType>().Where(x => x.Id == pbma.MaterialTypeId).FirstOrDefaultAsync();
                    //    PrintQueue pq1 = new PrintQueue();
                    //    pq1.Id = pbma.Id;
                    //    pq1.No = "1";
                    //    pq1.QrCode = pbma.QrCode;
                    //    pq1.Name = pbma.Name;
                    //    pq1.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    //    pq1.Dept = bdata.Name;
                    //    pq1.TypeName = tydata.Name;
                    //    pq1.Type = Skill_Type.Material.ToString();
                    //    pq1.Status = "0";
                    //    pq1.Printer = _operator?.Property.Printer;
                    //    listdata.Add(pq1);
                    //    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                    //    return 1;
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 微信扫一扫识别物料二维码
        /// </summary>
        /// <param name="QrCode"></param>
        /// <returns></returns>
        public async Task<ScanInfoByWX> GetMaterialInfoByScanAsync(string QrCode)
        {
            //    StringBuilder sql = new StringBuilder();
            //    sql.Append("SELECT ");
            //    sql.Append("a.MaterialName Name,");
            //    sql.Append("b.Spec,");
            //    sql.Append("b.Ofmaterial,");
            //    sql.Append("a.Id,");
            //    sql.Append("b.Code,");
            //    sql.Append("DATE_FORMAT(c.CreateTime,'%Y-%m-%d %H:%i') MakeDate,");
            //    sql.Append("c.DeptId Company ");
            //    sql.Append("FROM ");
            //    sql.Append("PB_JobBookingQrCode a ");
            //    sql.Append("LEFT JOIN PB_Material b on a.MaterialId=b.Id ");
            //    sql.Append("LEFT JOIN PB_PackList c on a.PackId=c.Id ");
            //    sql.Append("WHERE ");
            //    sql.Append("a.QrCode = '" + QrCode + "'");
            //    var result = await Db.GetListBySqlAsync<ScanInfoByWX>(sql.ToString());
            //    if (result.Count > 0)
            //    {
            //        sql.Clear();
            //        sql.Append("SELECT ");
            //        sql.Append("Name,");
            //        sql.Append("FullName ");
            //        sql.Append("FROM ");
            //        sql.Append("Base_Department ");
            //        sql.Append("WHERE ");
            //        sql.Append("FIND_IN_SET(");
            //        sql.Append("Id,");
            //        sql.Append("getParentlist ('" + result[0].Company + "')) ");
            //        sql.Append("AND Type = 1 ");
            //        sql.Append("AND ParentId IS NOT NULL");
            //        var company = await Db.GetListBySqlAsync<ScanInfoCoName>(sql.ToString());
            //        result[0].Company = company[0].FullName;
            //        return result[0];
            //    }
            //    return null;
            //获取扫描的数据表头是成品还是单个物料

            try
            {
                var packmodel = QrCode.Split(',')?[0];
                string MaterialId = string.Empty;
                //验证扫描的是单个物料
                if (packmodel == "04")
                {
                    var model = QrCode.Split(',');
                    if (model.Length > 2)
                    {
                        if (model.Length < 4)
                        {
                            throw new BusException("请扫描物料二维码或手动输入");
                        }
                        else
                        {
                            MaterialId = model?[3].ToString();
                        }
                    }
                    else
                    {
                        MaterialId = model?[1].ToString();
                    }
                    Expression<Func<PB_Material, Base_Department, ScanInfoByWX>> select = (a, b) => new ScanInfoByWX
                    {
                        Name = a.Name,
                        Code = a.Code,
                        Spec = a.Spec,
                        Id = a.Id,
                        Company = b.Name,
                        MakeDate = a.CreateTime.ToString(),
                        Ofmaterial = a.Ofmaterial,
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_Material>().AsExpandable()
                            join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            select @select.Invoke(a, b);
                    var data = await q.Where(m => m.Id == MaterialId).FirstOrDefaultAsync();
                    if (data == null)
                    {
                        throw new BusException("未查询到物料信息");
                    }
                    return data;
                }
                else if (packmodel == "14")
                {
                    MaterialId = QrCode.Split(',')?[1].ToString();
                    PB_JobBookingQrCode pB_JobBookingQr = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(m => m.Id == MaterialId).FirstOrDefaultAsync();
                    if (pB_JobBookingQr.IsNullOrEmpty())
                    {
                        return null;
                    }
                    Expression<Func<PB_JobBookingQrCode, PB_Material, Base_Department,PB_PackList, ScanInfoByWX>> select = (a, b, c,d) => new ScanInfoByWX
                    {
                        Name = b.Name,
                        Code = b.Code,
                        Spec = b.Spec,
                        Id = a.Id,
                        Company = c.Name,
                        MakeDate =d.CreateTime.ToString(),
                        Ofmaterial = b.Ofmaterial,
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                            join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<Base_Department>() on b.DeptId equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            join d in Db.GetIQueryable<PB_PackList>() on a.PackId equals d.Id into ad
                            from d in ad.DefaultIfEmpty()
                            select @select.Invoke(a, b, c,d);
                    var data = await q.Where(m => m.Id == MaterialId).FirstOrDefaultAsync();
                    if (data.IsNullOrEmpty())
                    {
                        return null;
                    }
                    return data;
                }
                else {
                    throw new BusException("请扫描正确的二维码");
                }
            }
            catch (Exception)
            {

                return null;
            }
         
        }


        /// <summary>
        /// 插入MongodbDTO
        /// </summary>
        /// <param name="servicecode">处理功法</param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task<Object> InsertMongodb(InsertMongodbDTO servicecode, MongoDBOptions _mongodbOptions)
        {
            if (!servicecode.SkillMethod.IsNullOrEmpty())
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                string strguid = Guid.NewGuid().ToString("N");
                int i = 0;
                switch (servicecode.SkillMethod)
                {
                    case Skill_Type.user:  //用户
                        var user = await Db.GetIQueryable<Base_User>().ToListAsync();

                        foreach (var item in user)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.RealName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "用户";
                            pq.Type = Skill_Type.user.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = user.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return user.Count();
                    case Skill_Type.equipment:
                        var device = await Db.GetIQueryable<Base_Device>().ToListAsync();
                        foreach (var item in device)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "设备";
                            pq.Type = Skill_Type.equipment.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = device.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return device.Count();
                    case Skill_Type.Location:
                        List<PB_Location> Location = new List<PB_Location>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            Location = Db.GetListBySqlAsync<PB_Location>("SELECT *  FROM PB_Location WHERE id IN (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            Location = Db.GetListBySqlAsync<PB_Location>("SELECT *  FROM PB_Location ").Result;
                        }

                        foreach (var item in Location)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "货位";
                            pq.Type = Skill_Type.Location.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = Location.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return Location.Count();
                    case Skill_Type.NoticeReceipt:
                        List<PB_WarehousingNotice> NoticeReceipt = new List<PB_WarehousingNotice>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            NoticeReceipt = Db.GetListBySqlAsync<PB_WarehousingNotice>("SELECT b.QrCode FROM PB_PackList a INNER JOIN PB_WarehousingNotice b on a.NoticeId = b.ID WHERE a.id in (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            NoticeReceipt = Db.GetListBySqlAsync<PB_WarehousingNotice>("SELECT *  FROM PB_WarehousingNotice ").Result;
                        }

                        foreach (var item in NoticeReceipt)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = "通知入库单";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "通知入库单";
                            pq.Type = Skill_Type.NoticeReceipt.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = NoticeReceipt.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return NoticeReceipt.Count();
                    case Skill_Type.StorArea:
                        List<PB_StorArea> PB_StorArea = new List<PB_StorArea>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            PB_StorArea = Db.GetListBySqlAsync<PB_StorArea>("SELECT a.QrCode FROM PB_StorArea a  WHERE a.id in (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            PB_StorArea = Db.GetListBySqlAsync<PB_StorArea>("SELECT a.QrCode  FROM PB_StorArea ").Result;
                        }
                        foreach (var item in PB_StorArea)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = item.Name;
                            pq.TypeName = "库区单";
                            pq.Type = Skill_Type.StorArea.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = PB_StorArea.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return PB_StorArea.Count();
                    case Skill_Type.Rack:
                        List<PB_Rack> Rack = new List<PB_Rack>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            Rack = Db.GetListBySqlAsync<PB_Rack>("SELECT *  FROM PB_Rack WHERE id IN (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            Rack = Db.GetListBySqlAsync<PB_Rack>("SELECT *  FROM PB_Rack ").Result;
                        }

                        foreach (var item in Rack)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "货架";
                            pq.Type = Skill_Type.Location.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = Rack.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return Rack.Count();
                    case Skill_Type.Station:
                        List<PB_Station> Station = new List<PB_Station>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            Station = Db.GetListBySqlAsync<PB_Station>("SELECT *  FROM PB_Station WHERE id IN (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            Station = Db.GetListBySqlAsync<PB_Station>("SELECT *  FROM PB_Station ").Result;
                        }

                        foreach (var item in Station)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "工位";
                            pq.Type = Skill_Type.Station.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = Station.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return Station.Count();
                    case Skill_Type.Material:
                        List<PB_Material> Material = new List<PB_Material>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            Material = Db.GetListBySqlAsync<PB_Material>("SELECT *  FROM PB_Material WHERE id IN (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            Material = Db.GetListBySqlAsync<PB_Material>("SELECT *  FROM PB_Material ").Result;
                        }
                        foreach (var item in Material)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.Name;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "物料";
                            pq.Type = Skill_Type.Material.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = Material.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return Material.Count();
                    case Skill_Type.ReprintBookingQr:
                        List<PB_JobBookingQrCode> JobBookingQrCode = new List<PB_JobBookingQrCode>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            JobBookingQrCode = Db.GetListBySqlAsync<PB_JobBookingQrCode>("SELECT *  FROM PB_JobBookingQrCode WHERE id IN (" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            JobBookingQrCode = Db.GetListBySqlAsync<PB_JobBookingQrCode>("SELECT *  FROM PB_JobBookingQrCode ").Result;
                        }
                        foreach (var item in JobBookingQrCode)
                        {
                            i++;
                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.MaterialName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = "";
                            pq.TypeName = "物料";
                            pq.Type = Skill_Type.Material.ToString();
                            pq.Status = "0";
                            pq.Printer = _operator?.Property.Printer;
                            pq.BatchNumber = strguid;
                            pq.JobCount = JobBookingQrCode.Count;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return JobBookingQrCode.Count();
                    case Skill_Type.WorkReport:
                        List<PB_JobBookingQrCodeMaterial> JobBookingCode = new List<PB_JobBookingQrCodeMaterial>();
                        if (!string.IsNullOrEmpty(string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")))
                        {
                            JobBookingCode = Db.GetListBySqlAsync<PB_JobBookingQrCodeMaterial>("SELECT  a.*,b.Spec,b.IsProduct,  c.`Name` DepartmentName, CASE WHEN b.IsProduct=TRUE THEN  b.ProductCode ELSE b.`Code` END AS codinfo,b.IsStandard  FROM    PB_JobBookingQrCode a LEFT  JOIN PB_JobBooking e on a.ParentId = e.Id LEFT JOIN Base_User f on e.ReportUserId = f.Id LEFT JOIN  PB_Material b  on a.MaterialId = b.Id LEFT JOIN  Base_Department c on f.FactoryId = c.Id WHERE a.ParentId IN(" + string.Format("'{0}'", string.Join(",", servicecode.Ids.ToArray()).Replace(",", "','")) + ")").Result;
                        }
                        else
                        {
                            JobBookingCode = Db.GetListBySqlAsync<PB_JobBookingQrCodeMaterial>("SELECT *  FROM PB_JobBookingQrCode ").Result;
                        }

                        foreach (var item in JobBookingCode)
                        {
                            i++;
                            var sql = "SELECT project.`Name`,buding.Buildingnumber FROM PB_JobBookingQrCode AS job LEFT JOIN PB_ProductionOrder AS orderdata ON job.OrderId = orderdata.Id  LEFT JOIN PB_DesignList AS List ON orderdata.DesignId = List.Id LEFT JOIN PB_Project AS project ON List.ProjectId = project.Id  LEFT JOIN PB_Buildingnumber AS buding ON List.BuildingNumberID = buding.Id WHERE  job.Id = '" + item.Id + "'";
                            List<JobProjectData> JobProjectData = await Db.GetListBySqlAsync<JobProjectData>(sql);

                            PrintQueue pq = new PrintQueue();
                            pq.Id = item.Id;
                            pq.No = item.Id;
                            pq.QrCode = item.QrCode;
                            pq.Name = item.MaterialName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            pq.Dept = item.DepartmentName;
                            pq.TypeName = item.Spec;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.IsProduct = item.IsProduct;
                            pq.Printer = servicecode.Pritntid;
                            pq.Code = item.codinfo;
                            pq.BatchNumber = strguid;
                            pq.JobCount = JobBookingCode.Count;
                            pq.ProjectName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Name;
                            pq.BuildingNumberName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Buildingnumber;
                            pq.IsStandard = item.IsStandard == false ? 0 : 1;
                            listdata.Add(pq);
                        }
                        await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                        return JobBookingCode.Count();
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }

        public async Task<PageResult<PB_JobBookingDetailedListDTO>> GetJobBookingDetailedListAsync(PageInput<PBJobBookingConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_JobBooking, Base_Device, PB_ProcecureSub, PB_ProductionOrderDetail, PB_ProductionOrder, PB_Material, PB_DesignList, PB_Project, PB_CirculationBill, PB_JobBookingDetailedListDTO>> select = (a, b, c, d, e, f, g, h, l) => new PB_JobBookingDetailedListDTO
            {
                DeviceName = b.Name,
                ProcecureSubId = c.Id,
                ProcecureSubName = c.Name,
                MaterialId = f.Id,
                MaterialCode = f.Code,
                MaterialName = f.Name,
                ProjectCode = h.Code,
                ProjectName = h.Name,
                TaskQuantity = l.TaskQuantity,
                Completedquantity = a.StatisticsNums,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Device>() on a.DeviceId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProcecureSub>() on b.ProcecureSubId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_ProductionOrder>() on d.ParentId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Material>() on a.MaterialId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_DesignList>() on e.DesignId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    join h in Db.GetIQueryable<PB_Project>() on g.ProjectId equals h.Id into ah
                    from h in ah.DefaultIfEmpty()
                    join l in Db.GetIQueryable<PB_CirculationBill>() on a.CirBillId equals l.Id into al
                    from l in al.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g, h, l);
            if (!search.StartDate.IsNullOrEmpty() && !search.EndDate.IsNullOrEmpty())
            {
                DateTime StartDate = Convert.ToDateTime(Convert.ToDateTime(search.StartDate).Date.ToString());
                DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(search.EndDate).Date.ToString()).AddDays(1).AddSeconds(-1);
                q = q.Where(x => StartDate <= x.ReportTime && x.ReportTime <= EndDate);
            }
            if (!search.UserNames.IsNullOrEmpty())
            {
                q = q.Where(x => search.UserNames.Contains(x.DeptId) || search.UserNames.Contains(x.ReportUserId));
            }
            if (!search.SubNames.IsNullOrEmpty())
            {
                q = q.Where(x => search.SubNames.Contains(x.ProcecureSubId));
            }
            q = q.OrderByDescending(x => x.ReportTime);
            q = q.Where(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.GetPageResultAsync(input);
        }

        public async Task<List<PB_JobBookingDTO>> GetQualityTestingListAsync(string OrderDetailQrCode)
        {
            //解析任务单明细二维码
            string[] usermodel = OrderDetailQrCode.Split(',');
            string OrderDetailId = usermodel[2].ToString();
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingDTO>> select = (a, b, c, d, e, f, g) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSpec = e.Spec,
                MaterialSimpleName = e.SimpleName,
                MaterialTypeName = f.Name,
                DeptName = g.Name,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber,
                IsProduct = e.IsProduct,
                ProductCode = e.ProductCode
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_MaterialType>() on e.MaterialTypeId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_Department>() on a.DeptId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            q = q.Where(w => w.ParentId == OrderDetailId && w.Status == 1);
            return await q.ToListAsync();
        }

        public async Task<List<PB_JobBookingDTO>> GetQualityTestingListInputAsync(string OrderDetailQrCode)
        {
            //解析任务单明细二维码
            string[] usermodel = OrderDetailQrCode.Split(',');
            string OrderDetailId = usermodel[1].ToString();
            Expression<Func<PB_JobBooking, PB_ProductionOrderDetail, Base_Device, PB_ProcecureSub, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingDTO>> select = (a, b, c, d, e, f, g) => new PB_JobBookingDTO
            {
                OrderDetailNums = b.Nums,
                OrderDetailQrCode = b.QrCode,
                DeviceCode = c.Code,
                DeviceName = c.Name,
                SubCode = d.Code,
                SubName = d.Name,
                MaterialCode = e.Code,
                MaterialName = e.Name,
                MaterialSpec = e.Spec,
                MaterialSimpleName = e.SimpleName,
                MaterialTypeName = f.Name,
                DeptName = g.Name,
                IsQuantity = e.IsQuantity,
                IsNumber = e.IsNumber,
                IsProduct = e.IsProduct,
                ProductCode = e.ProductCode
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrderDetail>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on c.ProcecureSubId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Material>() on b.MaterialId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_MaterialType>() on e.MaterialTypeId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_Department>() on a.DeptId equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            q = q.Where(w => w.ParentId == OrderDetailId && w.Status == 1);
            return await q.ToListAsync();
        }

        /// <summary>
        /// 统计
        /// </summary>
        /// <param name="data">质检信息</param>
        /// <param name="_mongodbOptions">Mongo</param>
        /// <param name="_redisOptions">redis获取流水号</param>
        /// 调整统计默认打印机   2022-03-01   赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task UpdataStatisticsListData(List<PB_JobBookingListDTO> data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            List<PB_JobBooking> addDetail = new List<PB_JobBooking>();
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();

            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            string workshopId = string.Empty;
            foreach (var item in data)
            {
                workshopId = item.WorkshopId;
            }
            //获取默认打印机信息
            PB_Printer printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.WorkshopId == workshopId && x.Type == "Printchejiandayin").FirstOrDefaultAsync();

            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            string sqlMain = "";
            foreach (var item in data)
            {
                PB_JobBooking pbjb = new PB_JobBooking();
                pbjb.Id = item.Id;
                pbjb.ParentId = item.ParentId;
                pbjb.Nums = item.Nums;
                pbjb.ReturnNums = item.ReturnNums;
                pbjb.TreatmentType = item.TreatmentType;
                pbjb.Reason = item.Reason;
                pbjb.DeviceId = item.DeviceId;
                pbjb.DeptId = item.DeptId;
                pbjb.ReportUserId = item.ReportUserId;
                pbjb.ReportUserName = item.ReportUserName;
                pbjb.ReportTime = item.ReportTime;
                pbjb.QualityUserId = item.QualityUserId;
                pbjb.QualityUserName = item.QualityUserName;
                pbjb.QualityTime = item.QualityTime;
                pbjb.StatisticsUserId = item.userqrcode.Split(',')[1].ToString();
                pbjb.StatisticsUserName = bdata.RealName;
                pbjb.StatisticsTime = DateTime.Now;
                pbjb.StatisticsNums = item.StatisticsNums;
                pbjb.TakeOverUserId = item.userqrcode.Split(',')[1].ToString();
                pbjb.TakeOverUserName = bdata.RealName;
                pbjb.TakeOverTime = DateTime.Now;
                pbjb.CreateTime = item.CreateTime;
                pbjb.CreatorId = item.CreatorId;
                pbjb.CreatorRealName = item.CreatorRealName;
                pbjb.MaterialId = item.MaterialId;
                pbjb.MaterialName = item.MaterialName;
                pbjb.WorkshopId = item.WorkshopId;
                pbjb.Status = 2; //状态：0=待质检；1=质检；2=统计
                pbjb.OldOrNew = item.OldOrNew;
                addDetail.Add(pbjb);

                List<PB_JobBookingQrCode> JobBookingQrCodelist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.ParentId == item.Id).ToListAsync();
                if (JobBookingQrCodelist.Count == 0)
                {
                    if (item.IsNumber == true)
                    {
                        for (int i = 0; i < item.StatisticsNums; i++)
                        {
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            jkcode.Id = jobcodeId;
                            jkcode.ParentId = item.Id;
                            jkcode.OrderId = item.OrderDetailQrCode.Split(',')[1].ToString();
                            jkcode.OrderDetailId = item.OrderDetailQrCode.Split(',')[2].ToString();
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.WorkshopId = item.WorkshopId;
                            jkcode.OldOrNew = item.OldOrNew;
                            jkcode.RecId = "";
                            listcode.Add(jkcode);
                        }
                        //操作明细插入mongo
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.ParentId = item.ParentId;
                        pbdata.Nums = item.StatisticsNums;
                        pbdata.DeptId = item.DeptId;
                        pbdata.DeviceId = item.DeviceId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 2;
                        pbdata.OldOrNew = item.OldOrNew;
                        pbdata.PrinterId = printerdata.Id;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        jkcode.Id = jobcodeId;
                        jkcode.ParentId = item.Id;
                        jkcode.OrderId = item.OrderDetailQrCode.Split(',')[1].ToString();
                        jkcode.OrderDetailId = item.OrderDetailQrCode.Split(',')[2].ToString();
                        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                        jkcode.MaterialId = item.MaterialId;
                        jkcode.MaterialName = item.MaterialName;
                        jkcode.WorkshopId = item.WorkshopId;
                        jkcode.OldOrNew = item.OldOrNew;
                        jkcode.RecId = "";
                        listcode.Add(jkcode);
                        //操作明细插入mongo
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.ParentId = item.ParentId;
                        pbdata.Nums = 1;
                        pbdata.DeptId = item.DeptId;
                        pbdata.DeviceId = item.DeviceId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 2;
                        pbdata.OldOrNew = item.OldOrNew;
                        pbdata.PrinterId = printerdata.Id;
                        pbdetailed.Add(pbdata);
                    }
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    //插入mongo报工操作明细
                    await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
                }

                //查询任务单明细信息
                var orderdetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == item.ParentId).FirstOrDefaultAsync();
                int sCompleteNums = Convert.ToInt32(orderdetaildata.CompleteNums) + Convert.ToInt32(item.StatisticsNums);
                if (sCompleteNums <= orderdetaildata.Productionquantity)
                {
                    //修改任务单明细已完成数量SQL
                    sqlMain = @"update PB_ProductionOrderDetail set CompleteNums=ifnull(CompleteNums,0)+'" + item.StatisticsNums + "'  where Id='" + item.ParentId + "'; ";
                    //统计完修改任务单明细已完成数量
                    await ExecuteSqlAsync(sqlMain);
                }
                if (sCompleteNums == orderdetaildata.Productionquantity)
                {
                    sqlMain = @"update PB_ProductionOrderDetail set State=1  where Id='" + item.ParentId + "'; ";
                    //统计完修改任务单明细的状态
                    await ExecuteSqlAsync(sqlMain);
                }

                //修改任务单是否为完成状态
                var orderdata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.ParentId == orderdetaildata.ParentId).ToListAsync();
                var detaillistdate = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.ParentId == orderdetaildata.ParentId && x.State == 1).ToListAsync();
                if (detaillistdate.Count == orderdata.Count)
                {
                    await ExecuteSqlAsync("update PB_ProductionOrder set Status=2 where Id='" + orderdetaildata.ParentId + "'");
                }

            }

            //listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
            //{
            //    Id = x.Key.Id,
            //    No = x.Key.No,
            //    Name = x.Key.Name,
            //    TypeName = x.Key.TypeName,
            //    Date = x.Key.Date,
            //    Dept = x.Key.Dept,
            //    QrCode = x.Key.QrCode,
            //    Type = x.Key.Type,
            //    Status = x.Key.Status,
            //    Printer = x.Key.Printer
            //}).ToList();
            ////插入mongo队列
            //await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);

            //统计完插入报工明细表二维码信息
            await Db.InsertAsync(listcode);
            //修改质检完后统计信息
            await Db.UpdateAsync(addDetail);
        }

        public async Task<PB_JobBooking> GetTheUserListData(PB_JobBookingQueryDTO querydata)
        {
            var q = GetIQueryable().Where(x => x.ReportUserId == querydata.userqrcode.Split(',')[1].ToString() && x.ParentId == querydata.OrderDetailQrCode.Split(',')[2].ToString() && x.Status == 0);
            q = q.Where(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.FirstOrDefaultAsync();
        }

        public async Task<PB_ProductionOrderDetailData> DelTheUserData(PB_JobBookingQueryDTO querydata)
        {
            //解析任务单明细二维码
            string[] usermodel = querydata.OrderDetailQrCode.Split(',');
            string Id = usermodel[2].ToString();
            PB_JobBooking jobdata = await Db.GetIQueryable<PB_JobBooking>().Where(x => x.ParentId == Id).FirstOrDefaultAsync();
            List<PB_JobBookingQrCode> listdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.ParentId == jobdata.Id).ToListAsync();
            if (listdata.Count > 0)
            {
                string sqlMain = @"delete from PB_JobBookingQrCode where ParentId='" + jobdata.Id + "'";
                await ExecuteSqlAsync(sqlMain);
            }
            await ExecuteSqlAsync("delete from PB_JobBooking where ReportUserId='" + querydata.userqrcode.Split(',')[1].ToString() + "' and ParentId='" + Id + "' and Status=0 ");

            DataTable dt = await Db.GetDataTableWithSqlAsync("select a.*,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.SimpleName as MaterialSimpleName,c.`Name` as MaterialTypeName,b.Spec as MaterialSpec,b.Price as MaterialPrice,b.QrCode as MaterialQrCode,d.`Name` as UnitGroupName,(a.Productionquantity-(SELECT IFNULL(SUM(Nums),0) FROM PB_JobBooking where ParentId=a.Id))  as WorkReportNum,e.IsRefurbishment from PB_ProductionOrderDetail as a left join PB_Material as b on a.MaterialId=b.Id left join PB_MaterialType as c on b.MaterialTypeId=c.Id left join Base_UnitGroup as d on b.UnitGroupId=d.Id left join PB_ProductionOrder as e on a.ParentId=e.Id where a.Id='" + Id + "'");
            Entity.DTO.PB_ProductionOrderDetailData qdata = new Entity.DTO.PB_ProductionOrderDetailData();
            foreach (DataRow dr in dt.Rows)
            {
                qdata.Id = dr["Id"].ToString();
                qdata.ParentId = dr["ParentId"].ToString();
                qdata.MaterialId = dr["MaterialId"].ToString();
                qdata.ProcecureId = dr["ProcecureId"].ToString();
                qdata.Nums = Convert.ToDouble(dr["Nums"]);
                qdata.Remarks = dr["Remarks"].ToString();
                qdata.StartDate = Convert.ToDateTime(dr["StartDate"]);
                qdata.EndDate = Convert.ToDateTime(dr["EndDate"]);
                qdata.CreateTime = Convert.ToDateTime(dr["CreateTime"]);
                qdata.CreatorId = dr["CreatorId"].ToString();
                qdata.Deleted = Convert.ToBoolean(dr["Deleted"]);
                qdata.HasCheck = Convert.ToBoolean(dr["HasCheck"]);
                qdata.QrCode = dr["QrCode"].ToString();
                qdata.WorkshopId = dr["WorkshopId"].ToString();
                qdata.StationId = dr["StationId"].ToString();
                qdata.Finishedproduct = dr["Finishedproduct"].ToString();
                qdata.Ofmaterial = dr["Ofmaterial"].ToString();
                qdata.Holespacing = dr["Holespacing"].ToString();
                qdata.Productionquantity = Convert.ToInt32(dr["Productionquantity"]);
                qdata.CompleteNums = Convert.ToDouble(dr["CompleteNums"]);
                qdata.MaterialCode = dr["MaterialCode"].ToString();
                qdata.MaterialName = dr["MaterialName"].ToString();
                qdata.MaterialSimpleName = dr["MaterialSimpleName"].ToString();
                qdata.MaterialTypeName = dr["MaterialTypeName"].ToString();
                qdata.MaterialSpec = dr["MaterialSpec"].ToString();
                qdata.MaterialQrCode = dr["MaterialQrCode"].ToString();
                qdata.UnitGroupName = dr["UnitGroupName"].ToString();
                qdata.WorkReportNum = Convert.ToDouble(dr["WorkReportNum"]);
                qdata.IsRefurbishment = Convert.ToInt32(dr["IsRefurbishment"]);
            }
            return qdata;
        }
        /// <summary>
        /// 获取登录人的打印机列表
        /// </summary>
        /// <param name="PrintType">打印机类型</param>
        /// <returns></returns>
        public async Task<List<Printers>> GetPrinterListDataAsync(string PrintType)
        {
            string deptids = string.Empty;
            //string parentId = string.Empty;
            //Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //var deptdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == bdata.DepartmentId).FirstOrDefaultAsync();
            //if (deptdata.ParentId.IsNullOrEmpty())
            //{
            //    deptids += "'" + deptdata.Id + "',";
            //}
            //else
            //{
            //    deptids += "'" + deptdata.Id + "',";
            //    parentId = deptdata.ParentId;
            //    do
            //    {
            //        var ddata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == parentId).FirstOrDefaultAsync();
            //        if (ddata.ParentId == null)
            //        {
            //            deptids += "'" + ddata.Id + "',";
            //            parentId = "";
            //        }
            //        else
            //        {
            //            deptids += "'" + ddata.Id + "',";
            //            parentId = ddata.ParentId;
            //        }
            //    } while (parentId != "");
            //}
            //deptids = deptids.Substring(0, deptids.Length - 1);
            List<string> deptdata = await _opdept.GetDeptIds();
            foreach (var item in deptdata)
            {
                deptids += "'" + item + "',";
            }
            deptids = deptids.Substring(0, deptids.Length - 1);
            string sqlMain = @"select a.Id,a.Name,a.Type,c.`Name` as TypeName,IFNULL(a.Status,0) as Status from PB_Printer as a left join Base_User as b on a.WorkshopId=b.DepartmentId join Base_EnumItem as c on a.Type=c.Value where a.Type='" + PrintType + "' and  a.WorkshopId in (" + deptids + ") group by a.Id,a.Name,a.Type,c.`Name`,`Status` ";
            List<Printers> listdata = await Db.GetListBySqlAsync<Printers>(sqlMain);
            return listdata;
        }

        /// <summary>
        /// PDA统计物料打印
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions">Mongo</param>
        /// <param name="_redisOptions">redis获取流水号</param>
        /// <returns></returns>
        [Transactional]
        public async Task ProductPrintAsync(ProductPrintData data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            var deptdata = await _opdept.GetOperatorDept();
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_JobBookingQrCodeDTO>> selectdata = (a, b) => new PB_JobBookingQrCodeDTO
            {
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                MaterialSpec = b.Spec,
                MaterialName = b.Name,
                MaterialCode = b.Code
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var qdata = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @selectdata.Invoke(a, b);
            var JobBookingQrCodelist = await qdata.Where(x => x.ParentId == data.JobId).ToListAsync();

            string timestamp = Guid.NewGuid().ToString("N");
            //获取默认打印机信息
            PB_Printer printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.WorkshopId == data.WorkshopId && x.Type == "Printchejiandayin").FirstOrDefaultAsync();
            if (printerdata == null)
            {
                throw new BusException("请先从系统默认打印机");
            }
            if (JobBookingQrCodelist.Count == 0)
            {
                Expression<Func<PB_ProductionOrderDetail, PB_Material, ProductDTO>> select = (a, b) => new ProductDTO
                {
                    IsNumber = b.IsNumber,
                    IsProduct = b.IsProduct,
                    ProductCode = b.ProductCode,
                    MaterialSpec = b.Spec,
                    MaterialName = b.Name,
                    MaterialCode = b.Code
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var orderdata = await q.Where(x => x.Id == data.OrderDetailId).FirstOrDefaultAsync();
                Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                //实例化Redis操作类
                _redisOptions.DbChannel = (int)Redis_Type.redis6;
                RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                if (orderdata.IsNumber == true)
                {
                    for (int i = 0; i < data.Num; i++)
                    {
                        PrintQueue pq = new PrintQueue();
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        pq.Id = IdHelper.GetId();
                        pq.Name = orderdata.MaterialName;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = deptdata.DeptName;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                        pq.TypeName = orderdata.MaterialSpec;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = printerdata.Id;
                        pq.IsProduct = orderdata.IsProduct;
                        pq.Code = orderdata.IsProduct == true ? orderdata.ProductCode : orderdata.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = data.Num;
                        listdata.Add(pq);
                        jkcode.Id = jobcodeId;
                        jkcode.ParentId = data.JobId;
                        jkcode.OrderId = orderdata.ParentId;
                        jkcode.OrderDetailId = data.OrderDetailId;
                        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                        jkcode.MaterialId = orderdata.MaterialId;
                        jkcode.MaterialName = orderdata.MaterialName;
                        jkcode.WorkshopId = data.WorkshopId;
                        jkcode.OldOrNew = 1;
                        jkcode.RecId = "";
                        listcode.Add(jkcode);
                    }
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = data.OrderDetailId;
                    pbdata.Nums = data.Num;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = data.PrinterId;
                    pbdetailed.Add(pbdata);
                }
                else if (orderdata.IsNumber == false)
                {
                    PrintQueue pq = new PrintQueue();
                    PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                    string jobcodeId = IdHelper.GetId();   //成品档案表ID
                    pq.Id = IdHelper.GetId();
                    pq.Name = orderdata.MaterialName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = deptdata.DeptName;
                    if (RedisSetHelper.Exists("QualityTestingNumber"))
                    {
                        string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                        if (redis.GetString("QualityTestingTime") == thedate)
                        {
                            redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                        else
                        {
                            redis.SetString("QualityTestingTime", thedate);
                            redis.SetString("QualityTestingNumber", "1");
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                    }
                    else
                    {
                        redis.SetString("QualityTestingNumber", "0");
                    }
                    pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                    pq.TypeName = orderdata.MaterialSpec;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = "0";
                    pq.Printer = printerdata.Id;
                    pq.IsProduct = orderdata.IsProduct;
                    pq.Code = orderdata.IsProduct == true ? orderdata.ProductCode : orderdata.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = 1;
                    listdata.Add(pq);
                    jkcode.Id = jobcodeId;
                    jkcode.ParentId = data.JobId;
                    jkcode.OrderId = orderdata.ParentId;
                    jkcode.OrderDetailId = data.OrderDetailId;
                    jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                    jkcode.MaterialId = orderdata.MaterialId;
                    jkcode.MaterialName = orderdata.MaterialName;
                    jkcode.WorkshopId = data.WorkshopId;
                    jkcode.OldOrNew = 1;
                    jkcode.RecId = "";
                    listcode.Add(jkcode);
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = data.OrderDetailId;
                    pbdata.Nums = 1;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = data.PrinterId;
                    pbdetailed.Add(pbdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                //插入mongo报工操作明细
                await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
                await Db.InsertAsync(listcode);
            }
            else
            {
                foreach (var item in JobBookingQrCodelist)
                {
                    PrintQueue pq = new PrintQueue();
                    pq.Id = IdHelper.GetId();
                    pq.Name = item.MaterialName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = deptdata.DeptName;
                    pq.No = item.Id + "," + item.SerialNumber;
                    pq.QrCode = item.QrCode;
                    pq.TypeName = item.MaterialSpec;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = "0";
                    pq.Printer = printerdata.Id;
                    pq.IsProduct = item.IsProduct;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = JobBookingQrCodelist.Count;
                    listdata.Add(pq);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            }

        }

        /// <summary>
        /// PDA报工物料打印
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions">Mongo</param>
        /// <param name="_redisOptions">redis获取流水号</param>
        /// <returns></returns>
        [Transactional]
        public async Task WorkProductPrintAsync(List<ProductPrintData> data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            var deptdata = await _opdept.GetOperatorDept();
            string workshopId = string.Empty;
            List<string> liststr = new List<string>();
            foreach (var item in data)
            {
                workshopId = item.WorkshopId;
                liststr.Add(item.OrderDetailId);
            }
            Expression<Func<PB_JobBooking, PB_Material, PB_JobBookingDTO>> select = (a, b) => new PB_JobBookingDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSimpleName = b.SimpleName,
                MaterialSpec = b.Spec,
                IsQuantity = b.IsQuantity,
                IsNumber = b.IsNumber,
                ProductCode = b.ProductCode,
                IsProduct = b.IsProduct
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //获取报工信息
            var jobdatalist = await q.Where(w => liststr.Contains(w.ParentId) && w.Status == 0).ToListAsync();
            //获取默认打印机信息
            PB_Printer printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.WorkshopId == workshopId && x.Type == "Printchejiandayin").FirstOrDefaultAsync();
            if (printerdata == null)
            {
                throw new BusException("请先从系统默认打印机");
            }
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            string timestamp = Guid.NewGuid().ToString("N");

            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            foreach (var item in jobdatalist)
            {
                PB_ProductionOrderDetail orderDetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == item.ParentId).FirstOrDefaultAsync();
                if (item.IsNumber == true)
                {
                    for (int i = 0; i < item.Nums; i++)
                    {
                        PrintQueue pq = new PrintQueue();
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        pq.Id = IdHelper.GetId();
                        pq.Name = item.MaterialName;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = deptdata.DeptName;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                        pq.TypeName = item.MaterialSpec;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = printerdata.Id;
                        pq.IsProduct = item.IsProduct;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = item.Nums;
                        listdata.Add(pq);
                        jkcode.Id = jobcodeId;
                        jkcode.ParentId = item.Id;
                        jkcode.OrderId = orderDetaildata.ParentId;
                        jkcode.OrderDetailId = item.ParentId;
                        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                        jkcode.MaterialId = item.MaterialId;
                        jkcode.MaterialName = item.MaterialName;
                        jkcode.WorkshopId = item.WorkshopId;
                        jkcode.OldOrNew = 1;
                        jkcode.RecId = "";
                        listcode.Add(jkcode);
                    }
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = item.ParentId;
                    pbdata.Nums = item.Nums;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = printerdata.Id;
                    pbdetailed.Add(pbdata);
                }
                else if (item.IsNumber == false)
                {
                    PrintQueue pq = new PrintQueue();
                    PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                    string jobcodeId = IdHelper.GetId();   //成品档案表ID
                    pq.Id = IdHelper.GetId();
                    pq.Name = item.MaterialName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = deptdata.DeptName;
                    if (RedisSetHelper.Exists("QualityTestingNumber"))
                    {
                        string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                        if (redis.GetString("QualityTestingTime") == thedate)
                        {
                            redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                        else
                        {
                            redis.SetString("QualityTestingTime", thedate);
                            redis.SetString("QualityTestingNumber", "1");
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                    }
                    else
                    {
                        redis.SetString("QualityTestingNumber", "0");
                    }
                    pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                    pq.TypeName = item.MaterialSpec;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = "0";
                    pq.Printer = printerdata.Id;
                    pq.IsProduct = item.IsProduct;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = 1;
                    listdata.Add(pq);
                    jkcode.Id = jobcodeId;
                    jkcode.ParentId = item.Id;
                    jkcode.OrderId = orderDetaildata.ParentId;
                    jkcode.OrderDetailId = item.ParentId;
                    jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                    jkcode.MaterialId = item.MaterialId;
                    jkcode.MaterialName = item.MaterialName;
                    jkcode.WorkshopId = item.WorkshopId;
                    jkcode.OldOrNew = 1;
                    jkcode.RecId = "";
                    listcode.Add(jkcode);
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = item.ParentId;
                    pbdata.Nums = 1;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 4;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = printerdata.Id;
                    pbdetailed.Add(pbdata);
                }
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            //插入mongo报工操作明细
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            await Db.InsertAsync(listcode);
        }

        /// <summary>
        /// PDA报工明细删除
        /// </summary>
        /// <param name="OrderDetailId">任务单明细Id</param>
        /// <returns></returns>
        public async Task DelOrderDetailAsync(string OrderDetailId)
        {
            string sqlMain = @" delete from PB_JobBookingQrCode where OrderDetailId='" + OrderDetailId + "' and ParentId is null ";
            await ExecuteSqlAsync(sqlMain);
        }


        #region   PC报工(喷涂报工)

        /// <summary>
        /// 通用接口(PC报工)
        /// </summary>
        /// <param name="QrCode">二维码</param>
        /// <returns></returns>
        public async Task<Object> GetUserInfoAsync(string QrCode)
        {
            if (!QrCode.IsNullOrEmpty())
            {
                string[] qrcodemodel = QrCode.Split(',');
                string juber = qrcodemodel[0].ToString();
                switch (juber)
                {
                    case "01":  //用户
                        var q = await Db.GetIQueryable<Base_User>().Where(x => x.Id == qrcodemodel[1].ToString() && x.EmployeStatus == false).FirstOrDefaultAsync();
                        if (q != null)
                        {
                            string startime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                            string endtime = DateTime.Now.ToString("yyyy-MM-dd");
                            Expression<Func<PB_Dispatch, PB_DispatchDetail, Base_Device, DeviceSubDTO>> selectdata = (a, b, c) => new DeviceSubDTO
                            {
                                SubId = b.SubId,
                                DeviceId = c.Id,
                                DeviceName = c.Name
                            };
                            selectdata = selectdata.BuildExtendSelectExpre();
                            var qdata = from a in Db.GetIQueryable<PB_Dispatch>().AsExpandable()
                                        join b in Db.GetIQueryable<PB_DispatchDetail>() on a.Id equals b.ParentId into ab
                                        from b in ab.DefaultIfEmpty()
                                        join c in Db.GetIQueryable<Base_Device>() on b.SubId equals c.ProcecureSubId into bc
                                        from c in bc.DefaultIfEmpty()
                                        select @selectdata.Invoke(a, b, c);
                            var devedata = await qdata.Where(x => x.StaffId.Contains(q.Id) && x.DispatchDate >= Convert.ToDateTime(startime) && x.DispatchDate <= Convert.ToDateTime(endtime)).ToListAsync();

                            var data = devedata.GroupBy(x => new { x.SubId, x.DeviceId, x.DeviceName }).Select(x => new { SubId = x.Key.SubId, DeviceId = x.Key.DeviceId, DeviceName = x.Key.DeviceName }).FirstOrDefault();

                            Base_Department detpdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == q.DepartmentId).FirstOrDefaultAsync();
                            //生成token,有效期一天
                            JWTPayload jWTPayload = new JWTPayload
                            {
                                UserId = q.Id,
                                Expire = DateTime.Now.AddDays(1)
                            };
                            string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
                            Base_UserPDALogDTO buser = new Base_UserPDALogDTO();
                            buser.Id = q.Id;
                            buser.CreateTime = q.CreateTime;
                            buser.CreatorId = q.CreatorId;
                            buser.Deleted = q.Deleted;
                            buser.UserName = q.UserName;
                            buser.Password = q.Password;
                            buser.QrCode = q.QrCode;
                            buser.RealName = q.RealName;
                            buser.Sex = q.Sex;
                            buser.UserCode = q.UserCode;
                            buser.Birthday = q.Birthday;
                            buser.DepartmentId = q.DepartmentId;
                            buser.Token = token;
                            buser.DeptName = detpdata.Name;
                            buser.FullName = detpdata.FullName;
                            buser.DateNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            buser.ProcecureSubId = data == null ? "" : data.SubId;
                            buser.DeviceId = data == null ? "" : data.DeviceId;
                            buser.DeviceName = data == null ? "" : data.DeviceName;
                            return buser;
                        }
                        else
                        {
                            throw new BusException("请扫描正确的用户二维码信息");
                        }
                    case "11":  //设备
                        var Devicedata = await Db.GetIQueryable<Base_Device>().Where(x => x.Id == qrcodemodel[3].ToString()).FirstOrDefaultAsync();
                        if (Devicedata != null)
                        {
                            return Devicedata;
                        }
                        else
                        {
                            throw new BusException("请扫描正确的设备二维码信息");
                        }
                    default:
                        return null;
                }
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 成品报工(最后一道工序)
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <param name="_redisOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task WorkReportPrintListAsync(WorkReportPrintData data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            //获取流转单id
            string circulationId = data.QrCode.Split(',')?[1].ToString();

            PB_OutsourcingBillUpList OutsourcingBillUpList = await Db.GetIQueryable<PB_OutsourcingBillUpList>().Where(x => x.CirBillId == circulationId).FirstOrDefaultAsync();
            if (OutsourcingBillUpList != null)
            {
                throw new BusException("已外协不能报工");
            }

            List<PB_DispatchGroup> dgdata = await Db.GetIQueryable<PB_DispatchGroup>().Where(x => x.CirBillId == circulationId).ToListAsync();
            if (dgdata.Count == 0)
            {
                throw new BusException("请先派工");
            }

            //设备id
            string DeviceId = data.DeviceQrCode;
            //包码打印机
            string packprinterId = string.Empty;
            //物料打印机
            string materialprinterId = string.Empty;

            //获取设备对应的打印机
            List<PB_Printer> printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.DeviceId == DeviceId).ToListAsync();
            if (printerdata.Count == 0)
            {
                throw new BusException("请先维护设备对应的打印机");
            }
            else
            {
                if (printerdata.Where(x => x.Type == "PrintPackage").FirstOrDefault() != null)
                {
                    packprinterId = printerdata.Where(x => x.Type == "PrintPackage").FirstOrDefault().Id;
                }
                else
                {
                    throw new BusException("请先维护设备对应的包码打印机");
                }
                if (printerdata.Where(x => x.Type == "PrintMaterial").FirstOrDefault() != null)
                {
                    materialprinterId = printerdata.Where(x => x.Type == "PrintMaterial").FirstOrDefault().Id;
                }
                else
                {
                    throw new BusException("请先维护设备对应的物料打印机");
                }
            }
            //获取设备信息
            Base_Device devicedata = await Db.GetIQueryable<Base_Device>().Where(x => x.Id == DeviceId).FirstOrDefaultAsync();

            //获取流转单的上件派工信息
            Expression<Func<PB_DispatchGroup, PB_DispatchDetail, PB_DispatchGroupDTO>> gselect = (a, b) => new PB_DispatchGroupDTO
            {
                JobNums = b.Nums
            };
            gselect = gselect.BuildExtendSelectExpre();
            var gq = from a in Db.GetIQueryable<PB_DispatchGroup>().AsExpandable()
                     join b in Db.GetIQueryable<PB_DispatchDetail>() on a.DispatchDetailId equals b.Id into ab
                     from b in ab.DefaultIfEmpty()
                     select @gselect.Invoke(a, b);
            var gdata = await gq.Where(x => x.CirBillId == circulationId).ToListAsync();
            var jdata = gdata.GroupBy(x => new { x.CirBillId }).Select(x => new { CirBillId = x.Key.CirBillId, Nums = x.Sum(i => i.JobNums) }).FirstOrDefault();
            if (jdata != null)
            {
                //获取流转单的报工信息
                List<PB_JobBooking> JobBooking = await Db.GetIQueryable<PB_JobBooking>().Where(x => x.CirBillId == circulationId).ToListAsync();
                var jobbookList = JobBooking.GroupBy(x => new { x.CirBillId }).Select(x => new { CirBillId = x.Key.CirBillId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();
                double? jobnums = jobbookList == null ? 0 : jobbookList.Nums;
                if (jdata.Nums == jobnums)
                {
                    throw new BusException("派工已完成,请勿重复扫描");
                }
            }
            else
            {
                throw new BusException("请先派工！");
            }
            //获取本次报工的信息
            Expression<Func<PB_CirculationBill, PB_DispatchGroup, PB_Material, PB_DispatchDetail, PB_ProductionOrder, PB_JobBooking, CirBillJobMaterial>> select = (a, b, c, d, e, f) => new CirBillJobMaterial
            {
                MaterialCode = c.Code,
                MaterialName = c.Name,
                MaterialSpec = c.Spec,
                IsNumber = c.IsNumber,
                ProductCode = c.ProductCode,
                IsProduct = c.IsProduct,
                IsStandard = c.IsStandard,
                PackageNum = c.PackageNum,
                IsSingle = c.IsSingle,
                DesignId = e.DesignId,
                ProjectId = d.ProjectId,
                DispatchNums = d.Nums,
                DetailId = d.Id,
                DispatchTime = d.CreateTime,
                JobBookId = f.Id
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_DispatchGroup>() on a.Id equals b.CirBillId into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.SubordinateProduct equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_DispatchDetail>() on b.DispatchDetailId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_ProductionOrder>() on d.OrderId equals e.Id into de
                    from e in de.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_JobBooking>() on d.Id equals f.DispatchDetailId into df
                    from f in df.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f);
            var CirculationBill = await q.Where(x => x.Id == circulationId && x.JobBookId == null).OrderBy(x => x.DispatchTime).FirstOrDefaultAsync();

            if (CirculationBill == null)
            {
                throw new BusException("请检查流转单对应的派工信息");
            }
            else
            {
                //获取本次上件报工的项目和楼号
                Expression<Func<PB_DesignList, PB_Project, PB_Buildingnumber, MaterialProjectDTO>> projectselect = (a, b, c) => new MaterialProjectDTO
                {
                    DesignId = a.Id,
                    ProjectId = a.ProjectId,
                    ProjectName = b.Name,
                    BuildingNumberID = a.BuildingNumberID,
                    BuildingNumberName = c.Buildingnumber
                };
                projectselect = projectselect.BuildExtendSelectExpre();
                var projectq = from a in Db.GetIQueryable<PB_DesignList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNumberID equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @projectselect.Invoke(a, b, c);
                var projectdata = await projectq.Where(x => x.DesignId == CirculationBill.DesignId).FirstOrDefaultAsync();


                //获取流转单已报工的数量
                List<PB_JobBooking> jobbooklist = await Db.GetIQueryable<PB_JobBooking>().Where(x => x.CirBillId == circulationId).ToListAsync();
                var jobbookdata = jobbooklist.GroupBy(x => new { x.CirBillId }).Select(x => new { CirBillId = x.Key.CirBillId, Nums = x.Sum(i => i.Nums) }).FirstOrDefault();
                double? amoutnums = 0;
                if (jobbookdata != null)
                {
                    amoutnums = jobbookdata.Nums + CirculationBill.DispatchNums;
                }
                else
                {
                    amoutnums = CirculationBill.DispatchNums;
                }
                //接收数量与（已报工数量加本次报工数量）相等托盘释放
                if (CirculationBill.ReceivingQuantity == amoutnums)
                {
                    string sqlMain = @" delete from PB_TrayCirculationBill where TrayId='" + CirculationBill.TrayId + "' and CirBillId='" + circulationId + "'; ";
                    await ExecuteSqlAsync(sqlMain);
                }
                if (CirculationBill.IsProduct == true)
                {
                    
                    Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                    //时间戳
                    string timestamp = GetTimeStamp();
                    //推送队列物料批次
                    string strguid = Guid.NewGuid().ToString("N");

                    //推送队列包批次
                    string packguid = Guid.NewGuid().ToString("N");

                    //实例化Redis操作类
                    _redisOptions.DbChannel = (int)Redis_Type.redis6;
                    RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                    List<PB_PackList> listpack = new List<PB_PackList>();
                    List<PB_PackListInfo> listinfo = new List<PB_PackListInfo>();
                    List<PrintQueue> listdata = new List<PrintQueue>();
                    List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
                    List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
                    List<PB_JobMaterial> jobmdata = new List<PB_JobMaterial>();
                    Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
                    var deptdata = await _opdept.GetOperatorDept();

                    //取流转单的统计数量,如果为0取报工数量
                    double? worknums = CirculationBill.DispatchNums;
                    //if (worknums == 0)
                    //{
                    //    throw new BusException("请扫描统计过的流转卡上件报工");
                    //}

                    //报工表
                    PB_JobBooking pB_Job = new PB_JobBooking();
                    string jobId = IdHelper.GetId();
                    pB_Job.Id = jobId;
                    pB_Job.ParentId = CirculationBill.TaskDetailId;
                    pB_Job.Nums = worknums;
                    pB_Job.ReturnNums = 0;
                    pB_Job.TreatmentType = "";
                    pB_Job.Reason = "";
                    pB_Job.DeviceId = DeviceId;
                    pB_Job.DeptId = bdata.FactoryId;
                    pB_Job.ReportTime = DateTime.Now;
                    pB_Job.ReportUserId = _operator.UserId;
                    pB_Job.ReportUserName = bdata.RealName;
                    pB_Job.TakeOverUserId = _operator.UserId;
                    pB_Job.TakeOverUserName = bdata.RealName;
                    pB_Job.TakeOverTime = DateTime.Now;
                    pB_Job.CreateTime = DateTime.Now;
                    pB_Job.CreatorId = _operator.UserId;
                    pB_Job.CreatorRealName = bdata.RealName;
                    pB_Job.Status = 0;
                    pB_Job.MaterialId = CirculationBill.SubordinateProduct;
                    pB_Job.MaterialName = CirculationBill.MaterialName;
                    pB_Job.Deleted = false;
                    pB_Job.WorkshopId = devicedata.WorkShopId;
                    pB_Job.OldOrNew = CirculationBill.Type;  //是翻新还是新制
                    pB_Job.JobType = 1;
                    pB_Job.CirBillId = CirculationBill.Id;
                    pB_Job.DispatchDetailId = CirculationBill.DetailId;
                    await Db.InsertAsync<PB_JobBooking>(pB_Job);

                    if (Convert.ToDecimal(CirculationBill.PackageNum) == 0)
                    {
                        throw new BusException("请维护物料的包装数量,物料包装数量不能为0");
                    }

                    //计算自动打包的数量
                    decimal packquantity = Math.Ceiling(Convert.ToDecimal(worknums) / Convert.ToDecimal(CirculationBill.PackageNum));
                    //是否是单个物料
                    if (CirculationBill.IsSingle == true && CirculationBill.IsNumber == false)
                    {
                        string strnum = string.Empty;
                        //生成成品Id
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                strnum = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                strnum = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        jkcode.Id = jobcodeId;
                        jkcode.ParentId = jobId;
                        jkcode.OrderId = CirculationBill.TaskId;
                        jkcode.OrderDetailId = CirculationBill.TaskDetailId;
                        jkcode.QrCode = h_Material + "," + CirculationBill.SubordinateProduct;
                        jkcode.MaterialId = CirculationBill.SubordinateProduct;
                        jkcode.MaterialName = CirculationBill.MaterialName;
                        jkcode.OldOrNew = CirculationBill.Type;
                        jkcode.WorkshopId = devicedata.WorkShopId;
                        jkcode.RecId = "";
                        jkcode.PackId = "";
                        jkcode.PackStatus = 0;
                        listcode.Add(jkcode);

                        for (int i = 0; i < worknums; i++)
                        {
                            //成品码推送
                            PrintQueue materprint = new PrintQueue();
                            materprint.Id = IdHelper.GetId();
                            materprint.No = jobcodeId + "," + strnum;
                            materprint.Name = CirculationBill.MaterialName;
                            materprint.TypeName = CirculationBill.MaterialSpec;
                            materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            materprint.Dept = deptdata.DeptName;
                            materprint.QrCode = h_Material + "," + CirculationBill.SubordinateProduct;
                            materprint.Type = Skill_Type.Statistics.ToString();
                            materprint.Status = "0";
                            materprint.Printer = materialprinterId;
                            materprint.IsProduct = CirculationBill.IsProduct;
                            materprint.Code = CirculationBill.IsProduct == true ? CirculationBill.ProductCode : CirculationBill.MaterialCode;
                            materprint.BatchNumber = strguid;
                            materprint.JobCount = worknums;
                            materprint.ProjectName = CirculationBill.IsStandard == false ? (projectdata == null ? "" : projectdata.ProjectName) : "";
                            materprint.BuildingNumberName = CirculationBill.IsStandard == false ? (projectdata == null ? "" : projectdata.BuildingNumberName) : "";
                            materprint.IsStandard = CirculationBill.IsStandard == false ? 0 : 1;
                            listdata.Add(materprint);
                        }
                        PB_JobMaterial jobdata = new PB_JobMaterial();
                        jobdata.Id = IdHelper.GetId();
                        jobdata.ParentId = jobId;
                        jobdata.MaterialId = CirculationBill.SubordinateProduct;
                        jobdata.Nums = worknums;
                        jobdata.Status = 0;
                        jobdata.CreatorId = _operator.UserId;
                        jobdata.CreateTime = DateTime.Now;
                        jobdata.Deleted = false;
                        jobdata.OrderId = CirculationBill.TaskId;
                        jobmdata.Add(jobdata);
                    }
                    //是否是序列化管理
                    else if (CirculationBill.IsNumber == true && CirculationBill.IsSingle == false)
                    {
                        double dcount = 0;  //已生成包的物料数量
                        double dindex = 0; //每个包的包装数量
                                           //计算推送队列的数量（成品数量+包的数量）
                        double jobcount = Convert.ToDouble(worknums) + Convert.ToDouble(packquantity);
                        for (int i = 0; i < packquantity; i++)
                        {
                            PrintQueue printdata = new PrintQueue();
                            PB_PackList packdata = new PB_PackList();
                            //包名称
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            //包id
                            string packId = IdHelper.GetId();

                            dcount = Convert.ToDouble(CirculationBill.PackageNum) * (i + 1);
                            if (dcount <= worknums)
                            {
                                dindex = Convert.ToDouble(CirculationBill.PackageNum);
                            }
                            else
                            {
                                dindex = Convert.ToDouble(worknums) - Convert.ToDouble(CirculationBill.PackageNum) * i;
                            }
                            for (int j = 0; j < dindex; j++)
                            {
                                if (j == 0)
                                {
                                    packdata.BoxName = CirculationBill.MaterialName;
                                    packdata.MaterialId = CirculationBill.SubordinateProduct;
                                    printdata.Name = CirculationBill.MaterialName;
                                    printdata.Code = CirculationBill.IsProduct == true ? CirculationBill.ProductCode : CirculationBill.MaterialCode;
                                    printdata.IsProduct = CirculationBill.IsProduct;
                                }
                                //生成成品Id
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                jkcode.Id = jobcodeId;
                                jkcode.ParentId = jobId;
                                jkcode.OrderId = CirculationBill.TaskId;
                                jkcode.OrderDetailId = CirculationBill.TaskDetailId;
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = CirculationBill.SubordinateProduct;
                                jkcode.MaterialName = CirculationBill.MaterialName;
                                jkcode.OldOrNew = CirculationBill.Type;
                                jkcode.WorkshopId = devicedata.WorkShopId;
                                jkcode.RecId = "";
                                jkcode.PackId = "";
                                jkcode.PackStatus = 0;
                                listcode.Add(jkcode);

                                ////成品插入包明细
                                //PB_PackListInfo infodata = new PB_PackListInfo();
                                //infodata.Id = IdHelper.GetId();
                                //infodata.PackId = packId;
                                //infodata.JobBookingId = jobcodeId;
                                //infodata.CreatorId = _operator.UserId;
                                //infodata.CreatorName = bdata.RealName;
                                //infodata.CreatorTime = DateTime.Now;
                                //infodata.Deleted = false;
                                //infodata.OldOrNew = CirculationBill.Type;
                                //listinfo.Add(infodata);

                                //成品码推送
                                PrintQueue materprint = new PrintQueue();
                                materprint.Id = IdHelper.GetId();
                                materprint.No = jobcodeId;
                                materprint.Name = CirculationBill.MaterialName;
                                materprint.TypeName = CirculationBill.MaterialSpec;
                                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                materprint.Dept = deptdata.DeptName;
                                materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                                materprint.Type = Skill_Type.Statistics.ToString();
                                materprint.Status = "0";
                                materprint.Printer = materialprinterId;
                                materprint.IsProduct = CirculationBill.IsProduct;
                                materprint.Code = CirculationBill.IsProduct == true ? CirculationBill.ProductCode : CirculationBill.MaterialCode;
                                materprint.BatchNumber = strguid;
                                materprint.JobCount = jobcount;
                                materprint.ProjectName = CirculationBill.IsStandard == false ? (projectdata == null ? "" : projectdata.ProjectName) : "";
                                materprint.BuildingNumberName = CirculationBill.IsStandard == false ? (projectdata == null ? "" : projectdata.BuildingNumberName) : "";
                                materprint.IsStandard = CirculationBill.IsStandard == false ? 0 : 1;
                                listdata.Add(materprint);

                            }

                            //每次成品码推送前把包信息放到成品码前面
                            PrintQueue pq = new PrintQueue();
                            pq.Id = IdHelper.GetId();
                            pq.No = packId;
                            pq.Name = "分割线";
                            pq.TypeName = "--------------------------";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = "";
                            pq.QrCode = h_Pack + "," + packId;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = materialprinterId;
                            pq.IsProduct = true;
                            pq.Code = "";
                            pq.BatchNumber = strguid;
                            pq.JobCount = jobcount;
                            pq.ProjectName = "";
                            pq.BuildingNumberName = "";
                            pq.IsStandard = CirculationBill.IsStandard == false ? 0 : 1;
                            listdata.Add(pq);

                            //包信息
                            packdata.Id = packId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.Status = 0;
                            packdata.Type = 1;
                            packdata.State = true;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorId = _operator.UserId;
                            packdata.Deleted = false;
                            packdata.CreatorName = bdata.RealName;
                            packdata.Nums = dindex;
                            packdata.QrCode = h_Pack + "," + packId;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.OldOrNew = CirculationBill.Type;
                            packdata.IsUnpacking = dindex == CirculationBill.PackageNum ? false : true;
                            listpack.Add(packdata);

                            //推送包信息到打印队列
                            printdata.Id = IdHelper.GetId();
                            printdata.No = packId;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = deptdata.DeptName;
                            printdata.BatchNumber = timestamp;
                            printdata.QrCode = h_Pack + "," + packId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = packprinterId;
                            printdata.TypeName = CirculationBill.MaterialSpec;
                            printdata.BatchNumber = packguid;
                            printdata.JobCount = Convert.ToDouble(packquantity);
                            printdata.ProjectName = "";
                            printdata.BuildingNumberName = "";
                            printdata.IsStandard = CirculationBill.IsStandard == false ? 0 : 1;
                            listdata.Add(printdata);

                        }

                        //生成成品记录
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = CirculationBill.Id;
                        pbdata.Nums = CirculationBill.WorkReportQuantity;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 4;
                        pbdata.OldOrNew = CirculationBill.Type;
                        pbdata.PrinterId = materialprinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        throw new BusException("物料信息有误,请先维护物料信息");
                    }
                    //else if (CirculationBill.IsNumber == false)
                    //{
                    //    double dcount = 0;  //已生成包的物料数量
                    //    double dindex = 0; //每个包的包装数量
                    //    for (int i = 0; i < packquantity; i++)
                    //    {
                    //        PrintQueue printdata = new PrintQueue();
                    //        PB_PackList packdata = new PB_PackList();
                    //        //包名称
                    //        string dataName = "bag_" + timestamp + "_" + (i + 1);
                    //        //包id
                    //        string packId = IdHelper.GetId();

                    //        dcount = Convert.ToDouble(CirculationBill.PackageNum) * (i + 1);
                    //        if (dcount <= worknums)
                    //        {
                    //            dindex = Convert.ToDouble(CirculationBill.PackageNum);
                    //        }
                    //        else
                    //        {
                    //            dindex = Convert.ToDouble(worknums) - Convert.ToDouble(CirculationBill.PackageNum) * i;
                    //        }
                    //        //生成成品Id
                    //        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                    //        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                    //        if (RedisSetHelper.Exists("QualityTestingNumber"))
                    //        {
                    //            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                    //            if (redis.GetString("QualityTestingTime") == thedate)
                    //            {
                    //                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                    //                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                    //            }
                    //            else
                    //            {
                    //                redis.SetString("QualityTestingTime", thedate);
                    //                redis.SetString("QualityTestingNumber", "1");
                    //                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                    //            }
                    //        }
                    //        else
                    //        {
                    //            redis.SetString("QualityTestingNumber", "0");
                    //        }
                    //        jkcode.Id = jobcodeId;
                    //        jkcode.ParentId = jobId;
                    //        jkcode.OrderId = CirculationBill.TaskId;
                    //        jkcode.OrderDetailId = "";
                    //        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                    //        jkcode.MaterialId = CirculationBill.SubordinateProduct;
                    //        jkcode.MaterialName = CirculationBill.MaterialName;
                    //        jkcode.OldOrNew = CirculationBill.Type;
                    //        jkcode.WorkshopId = devicedata.WorkShopId;
                    //        jkcode.RecId = "";
                    //        listcode.Add(jkcode);

                    //        ////成品插入包明细
                    //        //PB_PackListInfo infodata = new PB_PackListInfo();
                    //        //infodata.Id = IdHelper.GetId();
                    //        //infodata.PackId = packId;
                    //        //infodata.JobBookingId = jobcodeId;
                    //        //infodata.CreatorId = _operator.UserId;
                    //        //infodata.CreatorName = bdata.RealName;
                    //        //infodata.CreatorTime = DateTime.Now;
                    //        //infodata.Deleted = false;
                    //        //infodata.OldOrNew = CirculationBill.Type;
                    //        //listinfo.Add(infodata);


                    //        //成品码推送
                    //        for (int j = 0; j < CirculationBill.PackageNum; j++)
                    //        {
                    //            PrintQueue materprint = new PrintQueue();
                    //            materprint.Id = IdHelper.GetId();
                    //            materprint.No = jobcodeId;
                    //            materprint.Name = CirculationBill.MaterialName;
                    //            materprint.TypeName = CirculationBill.MaterialSpec;
                    //            materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    //            materprint.Dept = deptdata.DeptName;
                    //            materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                    //            materprint.Type = Skill_Type.Statistics.ToString();
                    //            materprint.Status = "0";
                    //            materprint.Printer = materialprinterId;
                    //            materprint.IsProduct = CirculationBill.IsProduct;
                    //            materprint.Code = CirculationBill.IsProduct == true ? CirculationBill.ProductCode : CirculationBill.MaterialCode;
                    //            materprint.BatchNumber = strguid;
                    //            materprint.JobCount = worknums + Convert.ToDouble(packquantity);
                    //            listdata.Add(materprint);
                    //        }

                    //        //每次成品码推送前把包信息放到成品码前面
                    //        PrintQueue pq = new PrintQueue();
                    //        pq.Id = IdHelper.GetId();
                    //        pq.No = packId;
                    //        pq.Name = "分割线";
                    //        pq.TypeName = "--------------------------";
                    //        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    //        pq.Dept = "";
                    //        pq.QrCode = h_Pack + "," + packId;
                    //        pq.Type = Skill_Type.Statistics.ToString();
                    //        pq.Status = "0";
                    //        pq.Printer = materialprinterId;
                    //        pq.IsProduct = true;
                    //        pq.Code = "";
                    //        pq.BatchNumber = strguid;
                    //        pq.JobCount = worknums + Convert.ToDouble(packquantity);
                    //        listdata.Add(pq);

                    //        //包信息
                    //        packdata.Id = packId;
                    //        packdata.DeptId = bdata.DepartmentId;
                    //        packdata.BoxNo = dataName;
                    //        packdata.BoxName = CirculationBill.MaterialName;
                    //        packdata.MaterialId = CirculationBill.SubordinateProduct;
                    //        printdata.Name = CirculationBill.MaterialName;
                    //        printdata.Code = CirculationBill.IsProduct == true ? CirculationBill.ProductCode : CirculationBill.MaterialCode;
                    //        printdata.IsProduct = CirculationBill.IsProduct;
                    //        packdata.Status = 0;
                    //        packdata.Type = 1;
                    //        packdata.State = true;
                    //        packdata.CreateTime = DateTime.Now;
                    //        packdata.CreatorId = _operator.UserId;
                    //        packdata.Deleted = false;
                    //        packdata.CreatorName = bdata.RealName;
                    //        packdata.Nums = dindex;
                    //        packdata.QrCode = h_Pack + "," + packId;
                    //        packdata.WorkshopId = bdata.DepartmentId;
                    //        packdata.OldOrNew = CirculationBill.Type;
                    //        packdata.IsUnpacking = dindex == CirculationBill.PackageNum ? false : true;
                    //        listpack.Add(packdata);

                    //        //推送包信息到打印队列
                    //        printdata.Id = IdHelper.GetId();
                    //        printdata.No = packId;
                    //        printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    //        printdata.Dept = deptdata.DeptName;
                    //        printdata.BatchNumber = timestamp;
                    //        printdata.QrCode = h_Pack + "," + packId;
                    //        printdata.Type = Skill_Type.Package.ToString();
                    //        printdata.Status = dindex.ToString();
                    //        printdata.Printer = packprinterId;
                    //        printdata.TypeName = CirculationBill.MaterialSpec;
                    //        printdata.BatchNumber = packguid;
                    //        printdata.JobCount = Convert.ToDouble(packquantity);
                    //        listdata.Add(printdata);

                    //    }

                    //    //生成成品记录
                    //    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    //    pbdata.Id = IdHelper.GetId();
                    //    pbdata.No = CirculationBill.Id;
                    //    pbdata.Nums = CirculationBill.WorkReportQuantity;
                    //    pbdata.DeptId = deptdata.DetpId;
                    //    pbdata.OperationUserId = _operator.UserId;
                    //    pbdata.OperationUserName = bdata.RealName;
                    //    pbdata.OperationTime = DateTime.Now;
                    //    pbdata.Type = 4;
                    //    pbdata.OldOrNew = CirculationBill.Type;
                    //    pbdata.PrinterId = materialprinterId;
                    //    pbdetailed.Add(pbdata);
                    //}
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
                    {
                        Id = x.Key.Id,
                        No = x.Key.No,
                        Name = x.Key.Name,
                        TypeName = x.Key.TypeName,
                        Date = x.Key.Date,
                        Dept = x.Key.Dept,
                        QrCode = x.Key.QrCode,
                        Type = x.Key.Type,
                        Status = x.Key.Status,
                        Printer = x.Key.Printer
                    }).ToList();
                    //插入mongo队列
                    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                    //插入mongo报工操作明细
                    await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
                    //插入包明细
                    //await Db.InsertAsync<PB_PackListInfo>(listinfo);
                    await Db.InsertAsync<PB_JobMaterial>(jobmdata);
                    //插入包信息
                    await Db.InsertAsync<PB_PackList>(listpack);
                    //统计完插入报工明细表二维码信息
                    await Db.InsertAsync(listcode);
                }
            }

        }

        /// <summary>
        /// 成品报工信息(最后一道工序)
        /// </summary>
        /// <param name="UserQrcode">报工人二维码</param>
        /// <returns></returns>
        public async Task<List<CirculationBillList>> GetCirculationBillListAsync(string UserQrcode)
        {
            string userid = UserQrcode.Split(',')?[1].ToString();
            string sqlMain = @"select ROW_NUMBER() over(order by a.ReportTime desc) as RowNum,DATE_FORMAT(a.ReportTime,'%Y-%m-%d  %H:%i:%S') AS SendTime,a.ReportUserId as WorkerId,a.ReportUserName as WorkerName,a.MaterialId,c.`Name` as MaterialName,a.Nums,a.DeviceId,d.`Name` as DeviceName,c.ProductCode MaterialCode,c.Spec as MaterialSpec from PB_JobBooking as a
left join PB_CirculationBill as b on a.CirBillId=b.Id
left join PB_Material as c on a.MaterialId=c.Id
left join Base_Device as d on a.DeviceId=d.Id
where a.ReportUserId='" + userid + "' and DATE_FORMAT(a.ReportTime,'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d')";
            List<CirculationBillList> listdata = await Db.GetListBySqlAsync<CirculationBillList>(sqlMain);
            return listdata;
        }


        #endregion

        #region  工序报工

        /// <summary>
        /// 工序报工
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<WorkProject> WorkingProcedureWorkReportAsync(WorkingProcedureData data)
        {
            //报工人Id
            string userId = data.UserQrCode.Split(',')?[1].ToString();
            //设备ID
            string deviceId = data.DeviceQrCode.Split(',')?[3].ToString();
            //托盘Id
            string trayId = data.TrayQrCode.Split(',')?[1].ToString();

            List<string> dispatchdetailIds = new List<string>();
            foreach (var item in data.DispatchDetailData)
            {
                dispatchdetailIds.Add(item.DispatchDetailId);
            }

            //获取用户信息
            Base_User user = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //获取设备信息
            Base_Device devicedata = await Db.GetIQueryable<Base_Device>().Where(x => x.Id == deviceId).FirstOrDefaultAsync();

            //获取工序信息
            PB_ProcecureSub subdata = await Db.GetIQueryable<PB_ProcecureSub>().Where(x => x.Id == devicedata.ProcecureSubId).FirstOrDefaultAsync();

            //获取派单明细信息
            Expression<Func<PB_DispatchDetail, PB_Project, PB_Material, PB_Dispatch, PB_ShiftType, PB_ProductionOrder, PB_Material, PB_DispatchDetailProjectDTO>> select = (a, b, c, d, e, f, g) => new PB_DispatchDetailProjectDTO
            {
                ProjectName = b.Name,
                MaterialWeight = c.Weight,
                MaterialName = c.Name,
                MaterialSpec = c.Spec,
                TeamTypeName = e.Name,
                OrderName = f.POName,
                SubId = a.SubId,
                SubordinateProductName = g.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_DispatchDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Dispatch>() on a.ParentId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_ShiftType>() on d.TeamType equals e.Id into de
                    from e in de.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_ProductionOrder>() on a.OrderId equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_Material>() on a.SubordinateProduct equals g.Id into ag
                    from g in ag.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            var detaildata = await q.Where(x => dispatchdetailIds.Contains(x.Id)).ToListAsync();

            //获取物料信息
            var materiaList = detaildata.GroupBy(x => new { x.Id, x.ParentId, x.MaterialId, x.MaterialName, x.MaterialSpec, x.MaterialWeight, x.OrderId, x.OrderDetailId, x.SubordinateProduct, x.OrderName, x.SubId, x.SubordinateProductName }).Select(x => new { Id = x.Key.Id, ParentId = x.Key.ParentId, MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, MaterialSpec = x.Key.MaterialSpec, MaterialWeight = x.Key.MaterialWeight, OrderId = x.Key.OrderId, OrderDetailId = x.Key.OrderDetailId, SubordinateProduct = x.Key.SubordinateProduct, OrderName = x.Key.OrderName, SubId = x.Key.SubId, SubordinateProductName = x.Key.SubordinateProductName, Nums = x.Sum(i => i.Nums) }).ToList();

            //相同项目下的物料信息
            var projectlist = detaildata.GroupBy(x => new { x.ProjectId, x.ProjectName, x.MaterialId }).Select(x => new { ProjectId = x.Key.ProjectId, ProjectName = x.Key.ProjectName, MaterialId = x.Key.MaterialId }).ToList();

            //获取班次信息
            var teamdata = detaildata.GroupBy(x => new { x.TeamTypeName }).Select(x => new { TeamTypeName = x.Key.TeamTypeName }).FirstOrDefault();

            List<PB_CirculationBill> cirlist = new List<PB_CirculationBill>();
            List<PB_TrayCirculationBill> traylist = new List<PB_TrayCirculationBill>();

            //获取流转单打印的信息
            WorkProject workdata = new WorkProject();
            foreach (var item in materiaList)
            {
                if (item.SubId != subdata.Id)
                {
                    throw new BusException("设备工序与派工单工序不一致不能报工");
                }

                //流转单Id
                string cirbillId = IdHelper.GetId();

                workdata.Title = "在制品流转卡";
                workdata.QrCode = h_Circulation + "," + cirbillId;
                workdata.SourceTitle = "派工单号";
                workdata.DispatchId = item.ParentId;
                workdata.OrderName = item.OrderName;
                workdata.UserName = user.RealName;
                workdata.SubName = subdata == null ? "" : subdata.Name;
                workdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                workdata.TeamTypeName = teamdata.TeamTypeName;
                workdata.MaterialName = item.MaterialName;
                workdata.SubordinateProductName = item.SubordinateProductName;
                workdata.MaterialSpec = item.MaterialSpec;

                //查询同一个项目同一种物料信息
                var itmelist = detaildata.Where(x => x.MaterialId == item.MaterialId).ToList();
                //定义同一个项目同一种物料报工数量和
                Double? dnum = data.DispatchDetailData.Where(x => x.DispatchDetailId == item.Id).FirstOrDefault().Nums;
                List<ProjectNumsData> prolist = new List<ProjectNumsData>();
                foreach (var itno in projectlist)
                {
                    //Double? pronums = 0;
                    //var DispatchDetaillist = detaildata.Where(x => x.ProjectId == itno.ProjectId && x.MaterialId == item.MaterialId).Select(x => new { DispatchDetailId = x.Id }).ToList();
                    //foreach (var items in DispatchDetaillist)
                    //{
                    //    dnum += data.DispatchDetailData.Where(x => x.DispatchDetailId == items.DispatchDetailId).FirstOrDefault().Nums;
                    //    pronums += data.DispatchDetailData.Where(x => x.DispatchDetailId == items.DispatchDetailId).FirstOrDefault().Nums;
                    //}
                    ProjectNumsData prodata = new ProjectNumsData();
                    prodata.ProjectId = itno.ProjectId;
                    prodata.ProjectName = itno.ProjectName;
                    prodata.Nums = dnum;
                    prolist.Add(prodata);
                }
                workdata.TaskQuantity = dnum;
                workdata.SingleWeight = item.MaterialWeight == null ? 0 : item.MaterialWeight;
                workdata.TotalWeight = (dnum * item.MaterialWeight) == null ? 0 : (dnum * item.MaterialWeight);
                workdata.ProjectData = prolist;


                //插入工序报工数据
                PB_CirculationBill cirblldata = new PB_CirculationBill();

                cirblldata.Id = cirbillId;
                cirblldata.CreateTime = DateTime.Now;
                cirblldata.CreatorId = _operator.UserId;
                cirblldata.Deleted = false;
                cirblldata.Type = 1;
                cirblldata.FactoryId = user.FactoryId;
                cirblldata.DeptId = user.DepartmentId;
                cirblldata.DeviceId = deviceId;
                cirblldata.TaskId = item.OrderId;
                cirblldata.TaskDetailId = item.OrderDetailId;
                cirblldata.DispatchId = item.ParentId;
                cirblldata.DispatchDetailId = item.Id;
                cirblldata.ProcedureId = devicedata.ProcecureSubId;
                cirblldata.TrayId = trayId;
                cirblldata.MaterialId = item.MaterialId;
                cirblldata.TaskQuantity = item.Nums;
                cirblldata.WorkReportQuantity = dnum;
                cirblldata.WorkerId = _operator.UserId;
                cirblldata.SendTime = DateTime.Now;
                cirblldata.StatisticalQuantity = 0;
                cirblldata.ReceivingQuantity = 0;
                cirblldata.Reamrk = workdata.ToJson();
                cirblldata.Status = 0;
                cirblldata.QrCode = h_Circulation + "," + cirbillId;
                cirblldata.LocationId = "";
                cirblldata.IsOutsourcing = false;
                cirblldata.SubordinateProduct = item.SubordinateProduct;
                cirlist.Add(cirblldata);

                //托盘与流转单关联
                PB_TrayCirculationBill traydata = new PB_TrayCirculationBill();
                traydata.Id = IdHelper.GetId();
                traydata.TrayId = trayId;
                traydata.CirBillId = cirbillId;
                traylist.Add(traydata);
            }

            //修改派工单明细已报工数量
            string sqlMain = string.Empty;
            foreach (var item in data.DispatchDetailData)
            {
                sqlMain += @" update PB_DispatchDetail set WorkReportQuantity=IFNULL(WorkReportQuantity,0)+" + item.Nums + " where Id='" + item.DispatchDetailId + "'; ";
            }
            await ExecuteSqlAsync(sqlMain);

            //foreach (var item in detaildata)
            //{
            //    WorkProject workdata = new WorkProject();
            //    workdata.ProjectId = item.ProjectId;
            //    workdata.ProjectName = item.ProjectName;
            //    workdata.JobNums = data.DispatchDetailData.Where(x => x.DispatchDetailId == item.Id).FirstOrDefault().Nums;
            //    workdata.DispatchDetailId = item.Id;
            //    workdata.OrderId = item.OrderId;

            //    //插入工序报工数据
            //    PB_CirculationBill cirblldata = new PB_CirculationBill();
            //    string cirbillId = IdHelper.GetId();
            //    cirblldata.Id = cirbillId;
            //    cirblldata.CreateTime = DateTime.Now;
            //    cirblldata.CreatorId = _operator.UserId;
            //    cirblldata.Deleted = false;
            //    cirblldata.Type = 1;
            //    cirblldata.FactoryId = user.FactoryId;
            //    cirblldata.DeptId = user.DepartmentId;
            //    cirblldata.DeviceId = deviceId;
            //    cirblldata.TaskId = item.OrderId;
            //    cirblldata.DispatchId = item.ParentId;
            //    cirblldata.DispatchDetailId = item.Id;
            //    cirblldata.ProcedureId = devicedata.ProcecureSubId;
            //    cirblldata.TrayId = trayId;
            //    cirblldata.MaterialId = item.MaterialId;
            //    cirblldata.TaskQuantity = item.Nums;
            //    cirblldata.WorkReportQuantity = data.DispatchDetailData.Where(x => x.DispatchDetailId == item.Id).FirstOrDefault().Nums;
            //    cirblldata.WorkerId = _operator.UserId;
            //    cirblldata.SendTime = DateTime.Now;
            //    cirblldata.StatisticalQuantity = 0;
            //    cirblldata.ReceivingQuantity = 0;
            //    cirblldata.Reamrk = workdata.ToJson();
            //    cirblldata.Status = 0;
            //    cirblldata.QrCode = h_Circulation + "," + cirbillId;
            //    cirlist.Add(cirblldata);

            //    PB_TrayCirculationBill traydata = new PB_TrayCirculationBill();
            //    traydata.Id = IdHelper.GetId();
            //    traydata.TrayId = trayId;
            //    traydata.CirBillId = cirbillId;
            //    traylist.Add(traydata);
            //}
            await Db.InsertAsync<PB_CirculationBill>(cirlist);
            await Db.InsertAsync<PB_TrayCirculationBill>(traylist);
            return workdata;
        }

        /// <summary>
        /// 获取工序报工的物料信息
        /// </summary>
        /// <param name="DispatchDetailQrCode">派工单明细二维码</param>
        /// <returns></returns>
        public async Task<PB_DispatchDetailProjectDTO> GetDispatchDetailProjectDataAsync(string DispatchDetailQrCode)
        {
            string dispatchdetailId = DispatchDetailQrCode.Split(',')?[1].ToString();
            //            string sqlMain = @"select DispatchId,DispatchDetailId,MaterialId,Nums from PB_CirculationBillItem where DispatchDetailId='{0}'
            //UNION ALL
            //select DispatchId,DispatchDetailId,MaterialId,Nums from PB_RawMaterialReceive where DispatchDetailId='{0}'";
            //            string sql = string.Format(sqlMain, dispatchdetailId);
            //            List<PickingDTO> listdata = await Db.GetListBySqlAsync<PickingDTO>(sql);
            //            if (listdata.Count == 0)
            //            {
            //                throw new BusException("未领料不能报工");
            //            }

            //获取工序报工物料信息
            Expression<Func<PB_DispatchDetail, PB_Project, PB_Material, PB_Material, PB_DispatchDetailProjectDTO>> select = (a, b, c, d) => new PB_DispatchDetailProjectDTO
            {
                ProjectName = b.Name,
                MaterialCode = c.Code,
                MaterialName = c.Name,
                MaterialSpec = c.Spec,
                JobNums = a.Nums - a.WorkReportQuantity,
                SubordinateProductName = d.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_DispatchDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Material>() on a.SubordinateProduct equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            var data = await q.Where(x => x.Id == dispatchdetailId).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new BusException("请扫描或输入正确的二维码信息");
            }
            else if (data.JobNums == 0)
            {
                throw new BusException("已完成报工");
            }
            PB_Dispatch Dispatch = await Db.GetIQueryable<PB_Dispatch>().Where(x => x.Id == data.ParentId && x.StaffId.Contains(_operator.UserId)).FirstOrDefaultAsync();
            if (Dispatch == null)
            {
                throw new BusException("请扫描自己的派工单进行报工");
            }
            return data;
        }

        /// <summary>
        /// 统计获取流转单的信息
        /// </summary>
        /// <param name="CirQrCode">流转单二维码</param>
        /// <returns></returns>
        public async Task<PB_CirculationBillDTO> GetCirculationBillDataAsync(string CirQrCode)
        {
            string cirbillId = CirQrCode.Split(',')?[1].ToString();
            //获取工序报工物料信息
            Expression<Func<PB_CirculationBill, PB_Material, PB_CirculationBillDTO>> select = (a, b) => new PB_CirculationBillDTO
            {
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                StatisticsNums = a.WorkReportQuantity - a.StatisticalQuantity
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var data = await q.Where(x => x.Id == cirbillId).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new BusException("请扫描或输入正确的二维码信息");
            }
            return data;
        }

        /// <summary>
        /// 接收获取流转单的信息
        /// </summary>
        /// <param name="CirQrCode">流转单二维码</param>
        /// <returns></returns>
        public async Task<PB_CirculationBillDTO> GetReceiveCirculationBillDataAsync(string CirQrCode)
        {
            string cirbillId = CirQrCode.Split(',')?[1].ToString();
            //获取工序报工物料信息
            Expression<Func<PB_CirculationBill, PB_Material, PB_CirculationBillDTO>> select = (a, b) => new PB_CirculationBillDTO
            {
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                ReceivingNums = a.StatisticalQuantity - a.ReceivingQuantity
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_CirculationBill>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var data = await q.Where(x => x.Id == cirbillId).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new BusException("请扫描或输入正确的二维码信息");
            }
            return data;
        }

        /// <summary>
        /// 接收流转单
        /// </summary>
        /// <param name="CirBillQrCode">流转单二维码</param>
        /// <param name="Nums">接收数量</param>
        /// <returns></returns>
        public async Task ReceiveCirculationBillAsync(string CirBillQrCode, Double? Nums)
        {
            string cirbillId = CirBillQrCode.Split(',')?[1].ToString();
            string sqlMain = @"update PB_CirculationBill set Receiver='" + _operator.UserId + "',ReceivingTime=NOW(),ReceivingQuantity='" + Nums + "' where Id='" + cirbillId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 流转单质检
        /// </summary>
        /// <param name="CirBillQrCode">流转单二维码</param>
        /// <param name="Nums">统计数量</param>
        /// <returns></returns>
        public async Task QualityCirculationBillAsync(string CirBillQrCode, Double? Nums)
        {
            string cirbillId = CirBillQrCode.Split(',')?[1].ToString();
            string sqlMain = @"update PB_CirculationBill set QualityUserId='" + _operator.UserId + "',QualityTime=NOW(),QualityNums='" + Nums + "' where Id='" + cirbillId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 流转单统计
        /// </summary>
        /// <param name="CirBillQrCode">流转单二维码</param>
        /// <param name="Nums">统计数量</param>
        /// <returns></returns>
        public async Task StatisticsCirculationBillAsync(string CirBillQrCode, Double? Nums)
        {
            string cirbillId = CirBillQrCode.Split(',')?[1].ToString();
            string sqlMain = @"update PB_CirculationBill set Statistician='" + _operator.UserId + "',StatisticalTime=NOW(),StatisticalQuantity='" + Nums + "' where Id='" + cirbillId + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 工序流转单补打
        /// </summary>
        /// <param name="DispatchDetailQrCode">派工单明细二维码</param>
        /// <returns></returns>
        public async Task<List<WorkProject>> GetCirculationBillPrintAsync(string DispatchDetailQrCode)
        {
            string dispatchdetailId = DispatchDetailQrCode.Split(',')?[1].ToString();
            PB_DispatchDetail ddata = await Db.GetIQueryable<PB_DispatchDetail>().Where(x => x.Id == dispatchdetailId).FirstOrDefaultAsync();
            List<PB_CirculationBill> listdata = await Db.GetIQueryable<PB_CirculationBill>().Where(x => x.DispatchId == ddata.ParentId && x.CreatorId == _operator.UserId && x.MaterialId == ddata.MaterialId).OrderByDescending(x => x.CreateTime).ToListAsync();
            List<WorkProject> worklist = new List<WorkProject>();
            foreach (var item in listdata)
            {
                WorkProject asdata = item.Reamrk.ToObject<WorkProject>();
                worklist.Add(asdata);
            }
            if (worklist.Count > 0)
            {
                return worklist;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        #endregion

        #region  翻新领料生成翻新出库流转卡

        /// <summary>
        /// 获取翻新出库的生产任务明细信息(作废)
        /// </summary>
        /// <param name="OrderDetailQrCode">任务单明细二维码</param>
        /// <returns></returns>
        public async Task<OrderDetailMaterialData> GetOrderDetailCirBillDataAsync(string OrderDetailQrCode)
        {
            //生产任务单明细Id
            string[] orderdetailmodel = OrderDetailQrCode.Split(',');
            string orderdetailId = "";
            if (orderdetailmodel.Length == 3)
            {
                orderdetailId = orderdetailmodel?[2].ToString();
            }
            else if (orderdetailmodel.Length == 2)
            {
                orderdetailId = orderdetailmodel?[1].ToString();
            }
            string sqlMain = @"select a.ParentId as OrderId,a.Id as OrderDetailId,a.QrCode,a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,a.Productionquantity,a.Productionquantity-(select IFNULL(SUM(WorkReportQuantity),0) from PB_CirculationBill where TaskId=a.ParentId and MaterialId=a.MaterialId) as JobSurplusNums from PB_ProductionOrderDetail as a join PB_Material as b on a.MaterialId=b.Id  where a.Id='" + orderdetailId + "'";
            var listdata = await Db.GetListBySqlAsync<OrderDetailMaterialData>(sqlMain);
            if (listdata.Count > 0)
            {
                if (listdata.FirstOrDefault().JobSurplusNums == 0)
                {
                    throw new BusException("已领料完成");
                }
                else
                {
                    PB_ProductionOrder orderdata = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == listdata.FirstOrDefault().OrderId && x.IsRefurbishment == 0).FirstOrDefaultAsync();
                    if (orderdata == null)
                    {
                        throw new BusException("请扫描翻新任务单");
                    }
                    return listdata.FirstOrDefault();
                }
            }
            else
            {
                throw new BusException("请扫描或输入正确的二维码信息");
            }
        }

        /// <summary>
        /// 翻新生产任务单生成翻新出库流转卡(作废)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<WorkProject> AddCirculationBillDataAsync(OrderDetailData data)
        {
            //托盘id
            string trayId = data.TrayQrCode.Split(',')?[1].ToString();
            //货位Id
            string locaId = data.LocaQrCode.Split(',')?[1].ToString();
            //任务单明细Id
            string[] orderdetailmodel = data.OrderDetailQrCode.Split(',');
            string orderdetailId = "";
            if (orderdetailmodel.Length == 3)
            {
                orderdetailId = orderdetailmodel?[2].ToString();
            }
            else if (orderdetailmodel.Length == 2)
            {
                orderdetailId = orderdetailmodel?[1].ToString();
            }

            //获取生产任务单明细物料信息
            Expression<Func<PB_ProductionOrderDetail, PB_Material, OrderDetailMaterialData>> select = (a, b) => new OrderDetailMaterialData
            {
                OrderId = a.ParentId,
                OrderDetailId = a.Id,
                MaterialId = a.MaterialId,
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                SingleWeight = b.Weight,
                TotalWeight = b.Weight * a.Productionquantity,
                Productionquantity = a.Productionquantity
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var materialdata = await q.Where(x => x.OrderDetailId == orderdetailId).FirstOrDefaultAsync();

            //获取操作人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //流转单Id
            string cirId = IdHelper.GetId();

            //获取流转单打印的信息
            WorkProject workdata = new WorkProject();
            List<ProjectNumsData> prolist = new List<ProjectNumsData>();
            workdata.Title = "翻新出库流转卡";
            workdata.QrCode = h_Circulation + "," + cirId;
            workdata.SourceTitle = "任务单号";
            workdata.DispatchId = materialdata.OrderId;
            workdata.UserName = userdata.RealName;
            workdata.SubName = "";
            workdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
            workdata.TeamTypeName = "";
            workdata.MaterialName = materialdata.MaterialName;
            workdata.MaterialSpec = materialdata.MaterialSpec;
            workdata.TaskQuantity = data.Nums;
            workdata.SingleWeight = materialdata.SingleWeight == null ? 0 : materialdata.SingleWeight;
            workdata.TotalWeight = materialdata.TotalWeight == null ? 0 : materialdata.TotalWeight;

            //获取生产任务单对应的项目信息
            Expression<Func<PB_ProductionOrder, PB_DesignList, PB_Project, OrderProjectData>> selectdata = (a, b, c) => new OrderProjectData
            {
                OrderId = a.Id,
                ProjectId = b.ProjectId,
                ProjectName = c.Name
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var qdata = from a in Db.GetIQueryable<PB_ProductionOrder>().AsExpandable()
                        join b in Db.GetIQueryable<PB_DesignList>() on a.DesignId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Project>() on b.ProjectId equals c.Id into bc
                        from c in bc.DefaultIfEmpty()
                        select @selectdata.Invoke(a, b, c);
            var prodata = await qdata.Where(x => x.OrderId == materialdata.OrderId).FirstOrDefaultAsync();
            if (prodata != null)
            {
                if (!prodata.ProjectId.IsNullOrEmpty())
                {
                    ProjectNumsData pro = new ProjectNumsData();
                    pro.ProjectId = prodata.ProjectId;
                    pro.ProjectName = prodata.ProjectName;
                    pro.Nums = data.Nums;
                    prolist.Add(pro);
                }
            }
            workdata.ProjectData = prolist;

            //生成翻新出库流转卡
            PB_CirculationBill cirdata = new PB_CirculationBill();
            cirdata.Id = cirId;
            cirdata.CreateTime = DateTime.Now;
            cirdata.CreatorId = _operator.UserId;
            cirdata.Deleted = false;
            cirdata.Type = 0;
            cirdata.FactoryId = userdata.FactoryId;
            cirdata.DeptId = userdata.DepartmentId;
            cirdata.DeviceId = "";
            cirdata.TaskId = materialdata.OrderId;
            cirdata.DispatchId = "";
            cirdata.DispatchDetailId = "";
            cirdata.ProcedureId = "";
            cirdata.TrayId = trayId;
            cirdata.MaterialId = materialdata.MaterialId;
            cirdata.TaskQuantity = materialdata.Productionquantity;
            cirdata.WorkReportQuantity = data.Nums;
            cirdata.WorkerId = _operator.UserId;
            cirdata.SendTime = DateTime.Now;
            cirdata.StatisticalQuantity = data.Nums;
            cirdata.Statistician = _operator.UserId;
            cirdata.StatisticalTime = DateTime.Now;
            cirdata.ReceivingQuantity = 0;
            cirdata.Reamrk = workdata.ToJson();
            cirdata.Status = 0;
            cirdata.QrCode = h_Circulation + "," + cirId;
            cirdata.LocationId = locaId;
            await Db.InsertAsync<PB_CirculationBill>(cirdata);

            return workdata;
        }

        /// <summary>
        /// 翻新领料
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<WorkProject> RefurbishmentPickingAsync(RefurbishmentData data)
        {
            string[] ordermodel = data.OrderQrCode.Split(',');
            string orderId = string.Empty;
            //获取操作人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            WorkProject workdata = new WorkProject();

            //生成任务单
            if (ordermodel[0] == "02")
            {
                orderId = ordermodel?[1].ToString();

                string packId = data.PackQrCode[0].Split(',')[1].ToString();

                //查询存库包的信息
                IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).FirstOrDefaultAsync();

                //获取生产任务单明细物料信息
                Expression<Func<PB_ProductionOrderDetail, PB_Material, OrderDetailMaterialData>> select = (a, b) => new OrderDetailMaterialData
                {
                    OrderId = a.ParentId,
                    OrderDetailId = a.Id,
                    MaterialId = a.MaterialId,
                    MaterialName = b.Name,
                    MaterialCode = b.Code,
                    MaterialSpec = b.Spec,
                    SingleWeight = b.Weight,
                    TotalWeight = b.Weight * a.Productionquantity,
                    Productionquantity = a.Productionquantity
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var materialdata = await q.Where(x => x.OrderId == orderId && x.MaterialId == LocalDetail.MaterialId).FirstOrDefaultAsync();

                //流转单Id
                string cirId = IdHelper.GetId();

                //获取流转单打印的信息
                List<ProjectNumsData> prolist = new List<ProjectNumsData>();
                workdata.Title = "翻新出库流转卡";
                workdata.QrCode = h_Circulation + "," + cirId;
                workdata.SourceTitle = "任务单号";
                workdata.DispatchId = orderId;
                workdata.UserName = userdata.RealName;
                workdata.SubName = "";
                workdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                workdata.TeamTypeName = "";
                workdata.MaterialName = materialdata.MaterialName;
                workdata.MaterialSpec = materialdata.MaterialSpec;
                workdata.TaskQuantity = LocalDetail.Num;
                workdata.SingleWeight = materialdata.SingleWeight == null ? 0 : materialdata.SingleWeight;
                workdata.TotalWeight = materialdata.TotalWeight == null ? 0 : materialdata.TotalWeight;

                //获取生产任务单对应的项目信息
                Expression<Func<PB_ProductionOrder, PB_DesignList, PB_Project, OrderProjectData>> selectdata = (a, b, c) => new OrderProjectData
                {
                    OrderId = a.Id,
                    ProjectId = b.ProjectId,
                    ProjectName = c.Name
                };
                selectdata = selectdata.BuildExtendSelectExpre();
                var qdata = from a in Db.GetIQueryable<PB_ProductionOrder>().AsExpandable()
                            join b in Db.GetIQueryable<PB_DesignList>() on a.DesignId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_Project>() on b.ProjectId equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            select @selectdata.Invoke(a, b, c);
                var prodata = await qdata.Where(x => x.OrderId == orderId).FirstOrDefaultAsync();
                if (prodata != null)
                {
                    if (!prodata.ProjectId.IsNullOrEmpty())
                    {
                        ProjectNumsData pro = new ProjectNumsData();
                        pro.ProjectId = prodata.ProjectId;
                        pro.ProjectName = prodata.ProjectName;
                        pro.Nums = LocalDetail.Num;
                        prolist.Add(pro);
                    }
                }
                workdata.ProjectData = prolist;

                //生成翻新出库流转卡
                PB_CirculationBill cirdata = new PB_CirculationBill();
                cirdata.Id = cirId;
                cirdata.CreateTime = DateTime.Now;
                cirdata.CreatorId = _operator.UserId;
                cirdata.Deleted = false;
                cirdata.Type = 0;
                cirdata.FactoryId = userdata.FactoryId;
                cirdata.DeptId = userdata.DepartmentId;
                cirdata.DeviceId = "";
                cirdata.TaskId = materialdata.OrderId;
                cirdata.DispatchId = "";
                cirdata.DispatchDetailId = "";
                cirdata.ProcedureId = "";
                cirdata.TrayId = LocalDetail.TrayId;
                cirdata.MaterialId = materialdata.MaterialId;
                cirdata.TaskQuantity = materialdata.Productionquantity;
                cirdata.WorkReportQuantity = LocalDetail.Num;
                cirdata.WorkerId = _operator.UserId;
                cirdata.SendTime = DateTime.Now;
                cirdata.StatisticalQuantity = LocalDetail.Num;
                cirdata.Statistician = _operator.UserId;
                cirdata.StatisticalTime = DateTime.Now;
                cirdata.ReceivingQuantity = 0;
                cirdata.Reamrk = workdata.ToJson();
                cirdata.Status = 0;
                cirdata.QrCode = h_Circulation + "," + cirId;
                cirdata.LocationId = LocalDetail.LocalId;
                cirdata.PackId = packId;
                cirdata.IsOutsourcing = false;
                cirdata.SubordinateProduct = materialdata.MaterialId;
                await Db.InsertAsync<PB_CirculationBill>(cirdata);
            }
            //外协任务单
            else if (ordermodel[0] == "29")
            {
                //任务单Id
                orderId = ordermodel?[1].ToString();

                //获取包集合
                List<string> packIds = new List<string>();
                foreach (var item in data.PackQrCode)
                {
                    packIds.Add(item.Split(',')?[1].ToString());
                }
                List<PB_CirculationBill> cirbilllist = new List<PB_CirculationBill>();
                //获取库内包信息
                Expression<Func<IT_LocalDetail, PB_PackList, PB_Material, CirPackListData>> select = (a, b, c) => new CirPackListData
                {
                    BoxName = b.BoxName,
                    MaterialSpec = c.Spec,
                    MaterialName = c.Name,
                    MaterialCode = c.Code,
                    SingleWeight = c.Width,
                    TotalWeight = a.Num * c.Width
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<IT_LocalDetail>().AsExpandable()
                        join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                List<CirPackListData> packlistdata = await q.Where(x => packIds.Contains(x.PackId)).ToListAsync();
                //获取外协任务单的明细信息
                Expression<Func<PB_OutsourcingBillDetail, PB_OutsourcingBill, PB_Project, PB_OutsourcingBillDetailProjectDTO>> selectdata = (a, b, c) => new PB_OutsourcingBillDetailProjectDTO
                {
                    ProjectId = b.ProjectId,
                    ProjectName = c.Name
                };
                selectdata = selectdata.BuildExtendSelectExpre();
                var qdata = from a in Db.GetIQueryable<PB_OutsourcingBillDetail>().AsExpandable()
                            join b in Db.GetIQueryable<PB_OutsourcingBill>() on a.ParentId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_Project>() on b.ProjectId equals c.Id into bc
                            from c in bc.DefaultIfEmpty()
                            select @selectdata.Invoke(a, b, c);
                var Outlistdata = await qdata.Where(x => x.ParentId == orderId).ToListAsync();


                //循环生成流转单
                foreach (var item in packlistdata)
                {
                    WorkProject wp = new WorkProject();
                    //流转单Id
                    string cirId = IdHelper.GetId();
                    //获取流转单打印的信息
                    List<ProjectNumsData> prolist = new List<ProjectNumsData>();
                    var itemdata = Outlistdata.Find(x => x.MaterialId == item.MaterialId);
                    wp.Title = "领料出库流转卡";
                    wp.QrCode = h_Circulation + "," + cirId;
                    wp.SourceTitle = "任务单号";
                    wp.DispatchId = orderId;
                    wp.UserName = userdata.RealName;
                    wp.SubName = "";
                    wp.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    wp.TeamTypeName = "";
                    wp.MaterialName = item.MaterialName;
                    wp.MaterialSpec = item.MaterialSpec;
                    wp.TaskQuantity = item.Num;
                    wp.SingleWeight = item.SingleWeight == null ? 0 : item.SingleWeight;
                    wp.TotalWeight = item.TotalWeight == null ? 0 : item.TotalWeight;

                    var itemproject = Outlistdata.Find(x => x.MaterialId == item.MaterialId);
                    if (itemproject != null)
                    {
                        if (!itemproject.ProjectId.IsNullOrEmpty())
                        {
                            ProjectNumsData pro = new ProjectNumsData();
                            pro.ProjectId = itemproject.ProjectId;
                            pro.ProjectName = itemproject.ProjectName;
                            pro.Nums = item.Num;
                            prolist.Add(pro);
                        }
                    }
                    wp.ProjectData = prolist;

                    //生成翻新出库流转卡
                    PB_CirculationBill cirdata = new PB_CirculationBill();
                    cirdata.Id = cirId;
                    cirdata.CreateTime = DateTime.Now;
                    cirdata.CreatorId = _operator.UserId;
                    cirdata.Deleted = false;
                    cirdata.Type = 0;
                    cirdata.FactoryId = userdata.FactoryId;
                    cirdata.DeptId = userdata.DepartmentId;
                    cirdata.DeviceId = "";
                    cirdata.TaskId = orderId;
                    cirdata.DispatchId = "";
                    cirdata.DispatchDetailId = "";
                    cirdata.ProcedureId = "";
                    cirdata.TrayId = item.TrayId;
                    cirdata.MaterialId = item.MaterialId;
                    cirdata.TaskQuantity = item.Num;
                    cirdata.WorkReportQuantity = item.Num;
                    cirdata.WorkerId = _operator.UserId;
                    cirdata.SendTime = DateTime.Now;
                    cirdata.StatisticalQuantity = item.Num;
                    cirdata.Statistician = _operator.UserId;
                    cirdata.StatisticalTime = DateTime.Now;
                    cirdata.ReceivingQuantity = 0;
                    cirdata.Reamrk = wp.ToJson();
                    cirdata.Status = 0;
                    cirdata.QrCode = h_Circulation + "," + cirId;
                    cirdata.LocationId = item.LocalId;
                    cirdata.PackId = item.PackId;
                    cirdata.IsOutsourcing = true;
                    cirbilllist.Add(cirdata);
                }
                await Db.InsertAsync<PB_CirculationBill>(cirbilllist);

                //List<TD_OutStorDetail> OutStorDetaillist = new List<TD_OutStorDetail>();
                //List<TD_OutStorRecord> OutStorRecordlist = new List<TD_OutStorRecord>();

                //var outpackidlist = packlistdata.GroupBy(x => new { x.StorId, x.LocalId, x.MaterialId, x.Price }).Select(x => new
                //{
                //    StorId = x.Key.StorId,
                //    LocalId = x.Key.LocalId,
                //    MaterialId = x.Key.MaterialId,
                //    Price = x.Key.Price,
                //    Nums = x.Sum(i => i.Num)
                //}).ToList();

                ////出库单Id
                //string outstorId = IdHelper.GetId();

                //double dbnum = 0;

                //foreach (var item in outpackidlist)
                //{
                //    TD_OutStorDetail outd = new TD_OutStorDetail();
                //    outd.Id = IdHelper.GetId();
                //    outd.StorId = item.StorId;
                //    outd.OutStorId = outstorId;
                //    outd.LocalId = item.LocalId;
                //    outd.AreaId = "";
                //    outd.RackId = "";
                //    outd.MaterialId = item.MaterialId;
                //    outd.OutNum = Convert.ToDouble(item.Nums);
                //    outd.Price = Convert.ToDouble(item.Price);
                //    outd.TotalAmt = Convert.ToDouble(item.Nums) * Convert.ToDouble(item.Price);
                //    outd.CreatorId = _operator.UserId;
                //    outd.CreateTime = DateTime.Now;
                //    outd.Deleted = false;
                //    OutStorDetaillist.Add(outd);

                //    TD_OutStorRecord outr = new TD_OutStorRecord();
                //    outr.Id = IdHelper.GetId();
                //    outr.StorId = item.StorId;
                //    outr.OutStorId = outstorId;
                //    outr.MaterialId = item.MaterialId;
                //    outr.OutNum = Convert.ToDouble(item.Nums);
                //    outr.Price = item.Price;
                //    outr.TotalAmt = item.Nums * item.Price;
                //    outr.CreateTime = DateTime.Now;
                //    outr.CreatorId = _operator.UserId;
                //    outr.Deleted = false;
                //    OutStorRecordlist.Add(outr);

                //    dbnum += Convert.ToDouble(item.Nums);
                //}

                //var stordata = packlistdata.GroupBy(x => new { x.StorId }).Select(x => new { StorId = x.Key.StorId }).FirstOrDefault();

                //var prodata = Outlistdata.GroupBy(x => new { x.ProjectId }).Select(x => new { ProjectId = x.Key.ProjectId }).FirstOrDefault();

                //TD_OutStorage outdata = new TD_OutStorage();
                //outdata.Id = outstorId;
                //outdata.Code = GetTimeStamp();
                //outdata.OutTime = DateTime.Now;
                //outdata.StorageId = stordata.StorId;
                //outdata.OutType = "OutSourcing";
                //outdata.RefCode = orderId;
                //outdata.ProjectId = prodata.ProjectId;
                //outdata.DesignId = "";
                //outdata.OutNum = dbnum;
                //outdata.CreatorId = _operator.UserId;
                //outdata.CreateTime = DateTime.Now;
                //outdata.Deleted = false;
                //outdata.QrCode = h_OutStorage + "," + outstorId;
                //outdata.DepId = userdata.FactoryId;
                //outdata.FactoryId = userdata.FactoryId;

                //await Db.InsertAsync<TD_OutStorDetail>(OutStorDetaillist);
                //await Db.InsertAsync<TD_OutStorRecord>(OutStorRecordlist);
                //await Db.InsertAsync<TD_OutStorage>(outdata);

                string upsql = @" update PB_OutsourcingBill set Status=3 where Id='" + orderId + "' ";
                await ExecuteSqlAsync(upsql);

            }
            return workdata;
        }

        /// <summary>
        /// 翻新领料(根据生产任务单明细输入数量)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<WorkProject> RefurMaterialPickingAsync(RefurMaterialData data)
        {
            //货位Id
            string locaId = data.LocaQrcode.Split(',')?[1].ToString();
            //托盘Id
            string trayId = data.TrayQrcode.Split(',')?[1].ToString();
            //生产任务单明细Id
            string orderdetailId = data.orderdetailQrcode.Split(',')?[2].ToString();
            //派工明细Id
            //string dispathId = data.DispatchDetailQrCode.Split(',')?[1].ToString();

            //获取操作人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            WorkProject workdata = new WorkProject();

            //获取生产任务单明细物料信息
            Expression<Func<PB_ProductionOrderDetail, PB_Material, PB_ProductionOrder, OrderDetailMaterialData>> select = (a, b, c) => new OrderDetailMaterialData
            {
                OrderId = a.ParentId,
                OrderDetailId = a.Id,
                MaterialId = a.MaterialId,
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                SingleWeight = b.Weight,
                TotalWeight = b.Weight * a.Productionquantity,
                Productionquantity = a.Productionquantity,
                OrderName = c.POName
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProductionOrder>() on a.ParentId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var materialdata = await q.Where(x => x.OrderDetailId == orderdetailId).FirstOrDefaultAsync();

            //流转单Id
            string cirId = IdHelper.GetId();

            #region  减库存,生成出库单

            //先查询库存信息
            List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.LocalId == locaId && x.MaterialId == materialdata.MaterialId).ToListAsync();
            if (LocalDetail.Count > 0)
            {
                PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();

                PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialdata.MaterialId).FirstOrDefaultAsync();

                //汇总当前货位的物料总数量
                var matersumnums = LocalDetail.GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId }).Select(x => new { MaterialId = x.Key.MaterialId, LocalId = x.Key.LocalId, StorId = x.Key.StorId, materNums = x.Sum(i => i.Num) }).FirstOrDefault();
                if (data.Nums > matersumnums.materNums)
                {
                    throw new BusException("请检查当前货位物料的数量是否满足出库的数量");
                }

                //获取要出库的物料数量
                double? warehouseNum = data.Nums;
                string sqlMain = string.Empty;

                foreach (var item in LocalDetail)
                {
                    var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                    if (trueorfalse.boolType == false)
                    {
                        throw new BusException("仓库物料正在盘点中禁止下架出库");
                    }
                    if (warehouseNum > 0)
                    {
                        //出库数量等于库存明细数量时
                        if (item.Num == warehouseNum)
                        {
                            warehouseNum -= item.Num;
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";

                        }
                        else if (item.Num < warehouseNum)   //出库数量大于库存明细数量时
                        {
                            if (warehouseNum >= item.Num)
                            {
                                warehouseNum -= item.Num;
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                            }
                            else
                            {
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                warehouseNum -= warehouseNum;
                            }
                        }
                        else if (item.Num > warehouseNum) //出库数量小于库存明细数量时
                        {
                            item.Num -= warehouseNum;
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                            warehouseNum -= warehouseNum;
                        }
                    }
                    else
                    {
                        continue;
                    }

                }

                await Db.ExecuteSqlAsync(sqlMain);

                //出库单Id
                string outstorId = IdHelper.GetId();

                //出库明细
                TD_OutStorDetail outd = new TD_OutStorDetail();
                outd.Id = IdHelper.GetId();
                outd.StorId = locadata.StorId;
                outd.OutStorId = outstorId;
                outd.LocalId = locadata.Id;
                outd.AreaId = locadata.AreaId;
                outd.RackId = locadata.RackId;
                outd.MaterialId = materialdata.MaterialId;
                outd.OutNum = Convert.ToDouble(data.Nums);
                outd.Price = Convert.ToDouble(Material.Price);
                outd.TotalAmt = Convert.ToDouble(data.Nums * Material.Price);
                outd.CreatorId = _operator.UserId;
                outd.CreateTime = DateTime.Now;
                outd.Deleted = false;
                await Db.InsertAsync<TD_OutStorDetail>(outd);

                //出库明细汇总
                TD_OutStorRecord outr = new TD_OutStorRecord();
                outr.Id = IdHelper.GetId();
                outr.StorId = locadata.StorId;
                outr.OutStorId = outstorId;
                outr.MaterialId = materialdata.MaterialId;
                outr.OutNum = Convert.ToDouble(data.Nums);
                outr.Price = Convert.ToDouble(Material.Price);
                outr.TotalAmt = Convert.ToDouble(data.Nums * Material.Price);
                outr.CreateTime = DateTime.Now;
                outr.CreatorId = _operator.UserId;
                outr.Deleted = false;
                await Db.InsertAsync<TD_OutStorRecord>(outr);

                //出库单
                TD_OutStorage outdata = new TD_OutStorage();
                outdata.Id = outstorId;
                outdata.Code = GetTimeStamp();
                outdata.OutTime = DateTime.Now;
                outdata.StorageId = locadata.StorId;
                outdata.OutType = "Refurbishment";
                outdata.RefCode = cirId;
                outdata.ProjectId = "";
                outdata.DesignId = "";
                outdata.OutNum = Convert.ToDouble(data.Nums);
                outdata.TotalAmt= Convert.ToDouble(data.Nums * Material.Price);
                outdata.CreatorId = _operator.UserId;
                outdata.CreateTime = DateTime.Now;
                outdata.Status = 0;
                outdata.Deleted = false;
                outdata.QrCode = h_OutStorage + "," + outstorId;
                outdata.DepId = userdata.FactoryId;
                outdata.FactoryId = userdata.FactoryId;
                await Db.InsertAsync<TD_OutStorage>(outdata);

                //增加出库日志
                PB_StockLog pblog = new PB_StockLog();
                pblog.Id = IdHelper.GetId();
                pblog.PackId = "";
                pblog.StorId = locadata.StorId;
                pblog.LocationId = locaId;
                pblog.MaterialId = materialdata.MaterialId;
                pblog.StockNumber = data.Nums;
                pblog.CreatorId = _operator.UserId;
                pblog.CreatorName = userdata.RealName;
                pblog.OperatorId = _operator.UserId;
                pblog.Type = 1;
                pblog.OrderID = cirId;
                pblog.CreateTime = DateTime.Now;
                pblog.State = 1;
                pblog.JobId = "";
                await Db.InsertAsync<PB_StockLog>(pblog);
            }
            else
            {
                throw new BusException("请检查库存物料是否存在");
            }

            #endregion

            //获取流转单打印的信息
            List<ProjectNumsData> prolist = new List<ProjectNumsData>();
            workdata.Title = "翻新出库流转卡";
            workdata.QrCode = h_Circulation + "," + cirId;
            workdata.SourceTitle = "任务单号";
            workdata.DispatchId = materialdata.OrderId;
            workdata.OrderName = materialdata.OrderName;
            workdata.UserName = userdata.RealName;
            workdata.SubName = "翻新领料";
            workdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
            workdata.TeamTypeName = "";
            workdata.MaterialName = materialdata.MaterialName;
            workdata.SubordinateProductName = materialdata.MaterialName;
            workdata.MaterialSpec = materialdata.MaterialSpec;
            workdata.TaskQuantity = data.Nums;
            workdata.SingleWeight = materialdata.SingleWeight == null ? 0 : materialdata.SingleWeight;
            workdata.TotalWeight = materialdata.TotalWeight == null ? 0 : materialdata.TotalWeight;

            //获取生产任务单对应的项目信息
            Expression<Func<PB_ProductionOrder, PB_DesignList, PB_Project, OrderProjectData>> selectdata = (a, b, c) => new OrderProjectData
            {
                OrderId = a.Id,
                ProjectId = b.ProjectId,
                ProjectName = c.Name
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var qdata = from a in Db.GetIQueryable<PB_ProductionOrder>().AsExpandable()
                        join b in Db.GetIQueryable<PB_DesignList>() on a.DesignId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Project>() on b.ProjectId equals c.Id into bc
                        from c in bc.DefaultIfEmpty()
                        select @selectdata.Invoke(a, b, c);
            var prodata = await qdata.Where(x => x.OrderId == materialdata.OrderId).FirstOrDefaultAsync();
            if (prodata != null)
            {
                if (!prodata.ProjectId.IsNullOrEmpty())
                {
                    ProjectNumsData pro = new ProjectNumsData();
                    pro.ProjectId = prodata.ProjectId;
                    pro.ProjectName = prodata.ProjectName;
                    pro.Nums = data.Nums;
                    prolist.Add(pro);
                }
            }
            workdata.ProjectData = prolist;

            //生成翻新出库流转卡
            PB_CirculationBill cirdata = new PB_CirculationBill();
            cirdata.Id = cirId;
            cirdata.CreateTime = DateTime.Now;
            cirdata.CreatorId = _operator.UserId;
            cirdata.Deleted = false;
            cirdata.Type = 0;
            cirdata.FactoryId = userdata.FactoryId;
            cirdata.DeptId = userdata.DepartmentId;
            cirdata.DeviceId = "";
            cirdata.TaskId = materialdata.OrderId;
            cirdata.TaskDetailId = materialdata.OrderDetailId;
            cirdata.DispatchId = "";
            cirdata.DispatchDetailId = "";
            cirdata.ProcedureId = "";
            cirdata.TrayId = trayId;
            cirdata.MaterialId = materialdata.MaterialId;
            cirdata.TaskQuantity = materialdata.Productionquantity;
            cirdata.WorkReportQuantity = data.Nums;
            cirdata.WorkerId = _operator.UserId;
            cirdata.SendTime = DateTime.Now;
            cirdata.StatisticalQuantity = data.Nums;
            cirdata.Statistician = _operator.UserId;
            cirdata.StatisticalTime = DateTime.Now;
            cirdata.ReceivingQuantity = 0;
            cirdata.Reamrk = workdata.ToJson();
            cirdata.Status = 0;
            cirdata.QrCode = h_Circulation + "," + cirId;
            cirdata.LocationId = locaId;
            cirdata.PackId = "";
            cirdata.IsOutsourcing = false;
            cirdata.QualityNums = data.Nums;
            cirdata.QualityTime = DateTime.Now;
            cirdata.QualityUserId = _operator.UserId;
            cirdata.TaskDetailId = materialdata.OrderDetailId;
            cirdata.Receiver = _operator.UserId;
            cirdata.ReceivingQuantity = data.Nums;
            cirdata.ReceivingTime = DateTime.Now;
            cirdata.SubordinateProduct = materialdata.MaterialId;
            await Db.InsertAsync<PB_CirculationBill>(cirdata);

            return workdata;
        }


        /// <summary>
        /// 翻新领料获取包信息
        /// </summary>
        /// <param name="PackQrCode">包二维码</param>
        /// <param name="OrderQrCode">任务单二维码</param>
        /// <returns></returns>
        public async Task<CirPackListData> GetCirPackListDataAsync(string PackQrCode, string OrderQrCode)
        {
            //包Id
            string packId = PackQrCode.Split(',')?[1].ToString();
            //任务单Id
            string orderId = OrderQrCode.Split(',')?[1].ToString();
            string[] ordermodel = OrderQrCode.Split(',');

            PB_CirculationBill billdata = await Db.GetIQueryable<PB_CirculationBill>().Where(x => x.PackId == packId).FirstOrDefaultAsync();
            if (billdata != null)
            {
                throw new BusException("已领取不能重复领取");
            }

            string sqlMain = @"select a.*,b.`Name` as BoxName,b.Spec as MaterialSpec,(concat(d.`Name`,'/',e.`Name`,'/',c.`Name`)) as LocalName,(concat(f.`Name`,f.`Code`)) as TrayName,(concat('13',',',a.PackId)) as PackQrCode from IT_LocalDetail as a join PB_Material as b on a.MaterialId=b.Id join PB_Location as c on a.LocalId=c.Id join PB_StorArea as d on c.AreaId=d.Id join PB_Rack as e on c.RackId=e.Id left join PB_Tray as f on a.TrayId=f.Id where a.PackId='" + packId + "'";
            List<CirPackListData> listdata = await Db.GetListBySqlAsync<CirPackListData>(sqlMain);
            if (listdata.Count > 0)
            {
                if (ordermodel[0].ToString() == "02")
                {
                    //Expression<Func<PB_ProductionOrderDetail, PB_CirculationBill, OrderDeatilMaterialData>> select = (a, b) => new OrderDeatilMaterialData
                    //{
                    //    OrderId = a.ParentId,
                    //    MaterialId = a.MaterialId,
                    //    Productionquantity = a.Productionquantity,
                    //    WorkReportQuantity = b.WorkReportQuantity,
                    //    IsOutsourcing = b.IsOutsourcing
                    //};
                    //select = select.BuildExtendSelectExpre();
                    //var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                    //        join b in Db.GetIQueryable<PB_CirculationBill>() on a.ParentId equals b.TaskId into ab
                    //        from b in ab.DefaultIfEmpty()
                    //        select @select.Invoke(a, b);
                    //var list = await q.Where(x => x.OrderId == orderId && x.MaterialId == listdata.FirstOrDefault().MaterialId).ToListAsync();
                    //var detdata = list.GroupBy(x => new { x.OrderId, x.MaterialId, x.Productionquantity }).Select(x => new { OrderId = x.Key.OrderId, MaterialId = x.Key.MaterialId, Productionquantity = x.Key.Productionquantity, Nums = x.Sum(i => i.WorkReportQuantity) }).FirstOrDefault();
                    sqlMain = @"select OrderId,MaterialId,Productionquantity,SUM(WorkReportQuantity) as WorkReportQuantity from ( select a.ParentId as OrderId,a.MaterialId,a.Productionquantity,b.WorkReportQuantity,b.IsOutsourcing from PB_ProductionOrderDetail as a left join PB_CirculationBill as b on a.ParentId=b.TaskId and a.MaterialId=b.MaterialId where a.ParentId='" + orderId + "' and a.MaterialId='" + listdata.FirstOrDefault().MaterialId + "')as t group by OrderId,MaterialId,Productionquantity";
                    List<OrderDeatilMaterialData> detdata = await Db.GetListBySqlAsync<OrderDeatilMaterialData>(sqlMain);
                    if (detdata.Count == 0)
                    {
                        throw new BusException("请检查包与任务单的物料信息是否匹配");
                    }
                    else
                    {
                        //计算当前包与已扫描包的合计数量
                        double dnum = Convert.ToDouble(listdata.FirstOrDefault().Num + detdata.FirstOrDefault().WorkReportQuantity);
                        if (dnum > detdata.FirstOrDefault().Productionquantity)
                        {
                            throw new BusException("已扫描的包的数量大于任务单的物料数量,请更换包或拆包后操作");
                        }
                    }
                }
                else if (ordermodel[0].ToString() == "29")
                {
                    //Expression<Func<PB_OutsourcingBillDetail, PB_CirculationBill, OrderDeatilMaterialData>> select = (a, b) => new OrderDeatilMaterialData
                    //{
                    //    OrderId = a.ParentId,
                    //    MaterialId = a.MaterialId,
                    //    Productionquantity = a.Qty,
                    //    WorkReportQuantity = b.WorkReportQuantity,
                    //    IsOutsourcing = b.IsOutsourcing
                    //};
                    //select = select.BuildExtendSelectExpre();
                    //var q = from a in Db.GetIQueryable<PB_OutsourcingBillDetail>().AsExpandable()
                    //        join b in Db.GetIQueryable<PB_CirculationBill>() on a.ParentId equals b.TaskId into ab
                    //        from b in ab.DefaultIfEmpty()
                    //        select @select.Invoke(a, b);
                    //var list = await q.Where(x => x.OrderId == orderId && x.MaterialId == listdata.FirstOrDefault().MaterialId).ToListAsync();
                    //var detdata = list.GroupBy(x => new { x.OrderId, x.MaterialId, x.Productionquantity }).Select(x => new { OrderId = x.Key.OrderId, MaterialId = x.Key.MaterialId, Productionquantity = x.Key.Productionquantity, Nums = x.Sum(i => i.WorkReportQuantity) }).FirstOrDefault();
                    sqlMain = @"select OrderId,MaterialId,Productionquantity,SUM(WorkReportQuantity) as WorkReportQuantity from ( select a.ParentId as OrderId,a.MaterialId,a.Qty as Productionquantity,b.WorkReportQuantity,b.IsOutsourcing from PB_OutsourcingBillDetail as a left join PB_CirculationBill as b on a.ParentId=b.TaskId and a.MaterialId=b.MaterialId where a.ParentId='" + orderId + "' and a.MaterialId='" + listdata.FirstOrDefault().MaterialId + "')as t group by OrderId,MaterialId,Productionquantity";
                    List<OrderDeatilMaterialData> detdata = await Db.GetListBySqlAsync<OrderDeatilMaterialData>(sqlMain);
                    if (detdata.Count == 0)
                    {
                        throw new BusException("请检查包与任务单的物料信息是否匹配");
                    }
                    else
                    {
                        //计算当前包与已扫描包的合计数量
                        double dnum = Convert.ToDouble(listdata.FirstOrDefault().Num + detdata.FirstOrDefault().WorkReportQuantity);
                        if (dnum > detdata.FirstOrDefault().Productionquantity)
                        {
                            throw new BusException("已扫描的包的数量大于任务单的物料数量,请更换包或拆包后操作");
                        }
                    }
                }
                return listdata.FirstOrDefault();
            }
            else
            {
                throw new BusException("请检查包是否存在库中");
            }

        }

        /// <summary>
        /// 翻新流转单补打
        /// </summary>
        ///  <param name="DispatchDetailQrCode">派工单明细二维码 </param>
        /// <returns></returns>
        public async Task<List<WorkProject>> GetOrderDetailCirBillPrintAsync(string DispatchDetailQrCode)
        {
            string dispatchdetailId = DispatchDetailQrCode.Split(',')?[1].ToString();
            PB_DispatchDetail ddata = await Db.GetIQueryable<PB_DispatchDetail>().Where(x => x.Id == dispatchdetailId).FirstOrDefaultAsync();
            if (ddata.IsNullOrEmpty())
            {
                throw new BusException("请扫描正确的派工单明细二维码");
            }
            List<PB_CirculationBill> listdata = await Db.GetIQueryable<PB_CirculationBill>().Where(x => x.DispatchId == ddata.ParentId && x.CreatorId == _operator.UserId && x.MaterialId == ddata.MaterialId).OrderByDescending(x => x.CreateTime).ToListAsync();
            List<WorkProject> worklist = new List<WorkProject>();
            foreach (var item in listdata)
            {
                WorkProject asdata = item.Reamrk.ToObject<WorkProject>();
                worklist.Add(asdata);
            }
            if (worklist.Count > 0)
            {
                return worklist;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 扫描生产任务单明细二维码获取物料信息
        /// </summary>
        /// <param name="orderdetailQrcode">生产任务单明细二维码</param>
        /// <param name="LocaQrcode">货位二维码</param>
        /// <returns></returns>
        public async Task<OrderDetailMaterialDTO> GetOrderDetailMaterialAsync(string orderdetailQrcode, string LocaQrcode)
        {
            string[] orderdetailmodel = orderdetailQrcode.Split(',');
            string orderdetailId = "";
            if (orderdetailmodel.Length == 3)
            {
                orderdetailId = orderdetailmodel?[2].ToString();
            }
            else
            {
                orderdetailId = orderdetailmodel?[1].ToString();
            }
            //货位Id
            string localId = LocaQrcode.Split(',')?[1].ToString();
            PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == localId).FirstOrDefaultAsync();

            //获取任务单明细信息
            Expression<Func<PB_ProductionOrderDetail, PB_Material, PB_CirculationBill, OrderDetailMaterialDTO>> select = (a, b, c) => new OrderDetailMaterialDTO
            {
                OrderDetailId = a.Id,
                OrderId = a.ParentId,
                Productionquantity = a.Productionquantity,
                MaterialId = a.MaterialId,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                WorkReportQuantity = c.WorkReportQuantity,
                QrCode = a.QrCode
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ProductionOrderDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_CirculationBill>() on new { OrderDetailId = a.Id, OrderId = a.ParentId } equals new { OrderDetailId = c.TaskDetailId, OrderId = c.TaskId } into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            List<OrderDetailMaterialDTO> data = await q.Where(x => x.OrderDetailId == orderdetailId).ToListAsync();

            var orderdata = data.GroupBy(x => new { x.OrderDetailId, x.OrderId, x.Productionquantity, x.MaterialId, x.MaterialCode, x.MaterialName, x.MaterialSpec, x.QrCode }).Select(x => new { OrderDetailId = x.Key.OrderDetailId, OrderId = x.Key.OrderId, Productionquantity = x.Key.Productionquantity, MaterialId = x.Key.MaterialId, MaterialCode = x.Key.MaterialCode, MaterialName = x.Key.MaterialName, MaterialSpec = x.Key.MaterialSpec, QrCode = x.Key.QrCode, WorkReportQuantity = x.Sum(i => i.WorkReportQuantity) }).FirstOrDefault();

            var trueorfalse = await _check.GetTrueOrFalse(orderdata.MaterialId, locadata.StorId, locadata.Id);
            if (trueorfalse.boolType == false)
            {
                throw new BusException("仓库物料正在盘点中禁止下架出库");
            }

            OrderDetailMaterialDTO OrderDetailData = new OrderDetailMaterialDTO();
            OrderDetailData.OrderDetailId = orderdata.OrderDetailId;
            OrderDetailData.OrderId = orderdata.OrderId;
            OrderDetailData.Productionquantity = orderdata.Productionquantity;
            OrderDetailData.MaterialId = orderdata.MaterialId;
            OrderDetailData.MaterialCode = orderdata.MaterialCode;
            OrderDetailData.MaterialName = orderdata.MaterialName;
            OrderDetailData.MaterialSpec = orderdata.MaterialSpec;
            OrderDetailData.WorkReportQuantity = orderdata.WorkReportQuantity;
            OrderDetailData.SurplusNums = (orderdata.Productionquantity - orderdata.WorkReportQuantity);
            OrderDetailData.QrCode = orderdata.QrCode;

            return OrderDetailData;
        }

        #endregion

        #region  大屏接口

        /// <summary>
        /// 大屏显示当日合格数(件)
        /// </summary>
        /// <param name="Day">前第几天</param>
        /// <returns>当日合格数(件)</returns>
        public ScreenDisplayValue3DTO GetTodayStatisticsNums(int Day)
        {
            string strSQL = @"SELECT IFNULL(SUM(IF(ReturnNums IS NULL OR ReturnNums=0,Nums,ReturnNums)),0) AS value
FROM PB_JobBooking 
WHERE JobType=1 AND OldOrNew=1 AND TO_DAYS(NOW())-TO_DAYS(ReportTime)=" + Day.ToString();
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            if (res != null)
            {
                //四舍五入保留两位小数
                return new Entity.DTO.ScreenDisplayValue3DTO { value = res.value.ToString("#0.##") + "件" };
            }
            return new Entity.DTO.ScreenDisplayValue3DTO { value = "0" + "件" };
        }
        /// <summary>
        /// 大屏显示当日不良品数(件)
        /// </summary>
        /// <param name="Day">前第几天</param>
        /// <returns>当日不良品数(件)</returns>
        public ScreenDisplayValue3DTO GetTodayNoPassNums(int Day)
        {
            string strSQL = @"SELECT IF(SUM(Nums)<SUM(ReturnNums),0,IFNULL(SUM(Nums),0)-IFNULL(SUM(IF(ReturnNums IS NULL OR ReturnNums=0,Nums,ReturnNums)),0)) AS value
FROM PB_JobBooking
WHERE JobType=1 AND OldOrNew=1 AND TO_DAYS(NOW())-TO_DAYS(ReportTime)=" + Day.ToString();
            var res = Db.GetListBySqlAsync<ScreenDisplayValueDTO>(strSQL).Result.FirstOrDefault();
            if (res != null)
            {
                //四舍五入保留两位小数
                return new Entity.DTO.ScreenDisplayValue3DTO { value = res.value.ToString("#0.##") + "件" };
            }
            return new Entity.DTO.ScreenDisplayValue3DTO { value = "0" + "件" };
        }
        /// <summary>
        /// 大屏显示当日良品率
        /// </summary>
        /// <param name="Day">前第几天</param>
        /// <returns>当日良品率</returns>
        public ScreenDisplayDashboardDTO GetTodayPassRate(int Day)
        {
            string strSQL = @"SELECT IF(IFNULL(SUM(Nums),0)=0,0,IFNULL(SUM(IF(ReturnNums IS NULL OR ReturnNums=0,Nums,ReturnNums)),0)/SUM(Nums)*100) AS value
FROM PB_JobBooking
WHERE JobType=1 AND OldOrNew=1 AND TO_DAYS(NOW())-TO_DAYS(ReportTime)=" + Day.ToString();
            var res = Db.GetListBySqlAsync<ScreenDisplayDashboardDTO>(strSQL).Result.FirstOrDefault();
            if (res != null)
            {
                //四舍五入保留两位小数
                res.value = Convert.ToDecimal(res.value.ToString("#0.##"));
            }
            return res;
        }
        /// <summary>
        /// 大屏显示指定车间当日质量合格率
        /// </summary>
        /// <param name="WorkShopName">车间名称,比如"A1车间","A4车间"</param>
        /// <param name="Day">前第几天</param>
        /// <returns>当日良品率</returns>
        public ScreenDisplayProgressDTO GetTodayPassRateByWorkShop(string WorkShopName, int Day)
        {
            string strSQL = @"SELECT IF(IFNULL(SUM(jb.Nums),0)=0,0,IFNULL(SUM(IF(ReturnNums IS NULL OR ReturnNums=0,Nums,ReturnNums)),0)/SUM(jb.Nums)*100) AS value
FROM PB_JobBooking jb
JOIN Base_Department d ON jb.WorkshopId=d.Id AND d.`Name` LIKE '%" + WorkShopName + @"%' AND jb.JobType=1 AND jb.OldOrNew=1 AND TO_DAYS(NOW())-TO_DAYS(ReportTime)=" + Day.ToString();
            var res = Db.GetListBySqlAsync<ScreenDisplayProgressDTO>(strSQL).Result.FirstOrDefault();
            if (res != null)
            {
                //四舍五入保留两位小数
                res.value = Convert.ToDecimal(res.value.ToString("#0.##"));
                res.data = res.value;
            }
            return res;
        }
        /// <summary>
        /// 大屏显示指定车间当月质量合格率
        /// </summary>
        /// <param name="WorkShopName">车间名称,比如"A1车间","A4车间"</param>
        /// <param name="Month">前第几月</param>
        /// <returns>当月质量合格率</returns>
        public ScreenDisplayProgressDTO GetMonthPassRate(string WorkShopName, int Month)
        {
            string strSQL = @"SELECT IF(IFNULL(SUM(jb.Nums),0)=0,0,IFNULL(SUM(IF(jb.ReturnNums IS NULL OR jb.ReturnNums=0,jb.Nums,jb.ReturnNums)),0)/SUM(jb.Nums)*100) AS value
FROM PB_JobBooking jb
JOIN Base_Department d ON jb.WorkshopId=d.Id AND d.`Name` LIKE '%" + WorkShopName + @"%' AND jb.JobType=1 AND jb.OldOrNew=1 AND date_format(jb.ReportTime, '%Y %m')=date_format(DATE_SUB(curdate(), INTERVAL " + Month.ToString() + @" MONTH),'%Y %m')
JOIN PB_ProductionOrderDetail pd ON jb.ParentId=pd.Id";
            var res = Db.GetListBySqlAsync<ScreenDisplayProgressDTO>(strSQL).Result.FirstOrDefault();
            if (res != null)
            {
                //四舍五入保留两位小数
                res.value = Convert.ToDecimal(res.value.ToString("#0.##"));
                res.data = res.value;
            }
            return res;
        }
        /// <summary>
        /// 大屏显示七日产量(吨)
        /// </summary>
        /// <param name="Day">前第几天</param>
        /// <returns>七日产量(吨)</returns>
        public PB_JobBooking7DayStatisticsNumsDTO GetSevenDaysStatisticsNums(int Day)
        {
            PB_JobBooking7DayStatisticsNumsDTO res = new PB_JobBooking7DayStatisticsNumsDTO();
            string strSQL = string.Empty;
            for (int i = 6; i > -1; i--)
            {
                strSQL = @"SELECT IFNULL(SUM(IF(jb.StatisticsNums IS NULL OR jb.StatisticsNums=0,jb.Nums,jb.StatisticsNums)*m.Weight),0)/1000 AS value
FROM PB_JobBooking jb
JOIN PB_Material m ON jb.MaterialId = m.Id AND jb.JobType=1 AND jb.OldOrNew=1 AND TO_DAYS(NOW())-TO_DAYS(jb.ReportTime)=" + (i + Day).ToString();
                var temp = Db.GetListBySql<ScreenDisplayValueDTO>(strSQL).FirstOrDefault().value;
                //保留两位小数
                temp = Convert.ToDouble(temp.ToString("#0.##"));
                res.series[0].data.Add(temp);
            }
            res.categories.Clear();
            for (int i = 6; i > -1; i--)
            {
                res.categories.Add(DateTime.Now.AddDays(-1 * (i + Day)).ToString("MM.dd"));
            }

            return res;
        }

        #endregion

        #region 维修改制

        /// <summary>
        /// 领料根据货位获取仓库物料信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<WXGZLocaMaterialDTO>> GetWXGZLocaMaterialListAsync(PageInput<WXGZConditionDTO> input)
        {
            var where = LinqHelper.True<WXGZLocaMaterialDTO>();
            var search = input.Search;
            Expression<Func<IT_LocalMaterial, PB_Material, View_StorAreaRackLocation, WXGZLocaMaterialDTO>> select = (a, b, c) => new WXGZLocaMaterialDTO
            {
                Id = a.Id,
                LocalId = a.LocalId,
                MaterialId = a.MaterialId,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                ProductCode = b.ProductCode,
                ScanNum = a.ScanNum,
                StorAreaName = c.StorAreaName
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<IT_LocalMaterial>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<View_StorAreaRackLocation>() on a.LocalId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<WXGZLocaMaterialDTO, bool>(
                   ParsingConfig.Default, false, $@"MaterialCode.Contains(@0) or MaterialName.Contains(@0) or ProductCode.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            string localid = search.LocalQrCode.Split(',')?[1].ToString();
            where = where.And(x => x.LocalId == localid);
            where = where.And(x => x.ScanNum > 0);
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 维修改制领料保存
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task SaveWXGZLocalMaterialDataAsync(WXGZmaterialData data)
        {
            //任务单明细Id
            string orderdetailid = data.OrderDetailQrCode.Split(',')?[2].ToString();

            //获取任务单明细信息
            PB_ProductionOrderDetail ProductionOrderDetail = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == orderdetailid).FirstOrDefaultAsync();

            //获取货位信息
            PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == data.WXGZLocalMaterial.LocalId).FirstOrDefaultAsync();

            var trueorfalse = await _check.GetTrueOrFalse(data.WXGZLocalMaterial.MaterialId, locadata.StorId, locadata.Id);
            if (trueorfalse.boolType == false)
            {
                throw new BusException("仓库物料正在盘点中禁止下架出库");
            }

            //获取
            List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == data.WXGZLocalMaterial.MaterialId && x.LocalId == data.WXGZLocalMaterial.LocalId).ToListAsync();

            //获取要出库的物料数量
            double? warehouseNum = data.WXGZLocalMaterial.Nums;
            string sqlMain = string.Empty;

            //减库存
            foreach (var item in LocalDetail)
            {
                if (warehouseNum > 0)
                {
                    //出库数量等于库存明细数量时
                    if (item.Num == warehouseNum)
                    {
                        warehouseNum -= item.Num;
                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";

                    }
                    else if (item.Num < warehouseNum)   //出库数量大于库存明细数量时
                    {
                        if (warehouseNum >= item.Num)
                        {
                            warehouseNum -= item.Num;
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                        }
                        else
                        {
                            if (item.OldOrNew == 0)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            else if (item.OldOrNew == 1)
                            {
                                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                            }
                            sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                            warehouseNum -= warehouseNum;
                        }
                    }
                    else if (item.Num > warehouseNum) //出库数量小于库存明细数量时
                    {
                        item.Num -= warehouseNum;
                        if (item.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        else if (item.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                        }
                        sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                        warehouseNum -= warehouseNum;
                    }
                }
                else
                {
                    continue;
                }

            }

            sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-"+ data.WXGZLocalMaterial.Nums +" where Id='" + data.WXGZLocalMaterial.MaterialId +"'; ";

            await Db.ExecuteSqlAsync(sqlMain);

            //物料信息
            PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == data.WXGZLocalMaterial.MaterialId).FirstOrDefaultAsync();

            //登录人信息
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //增加出库日志
            PB_StockLog pblog = new PB_StockLog();
            pblog.Id = IdHelper.GetId();
            pblog.PackId = "";
            pblog.StorId = locadata.StorId;
            pblog.LocationId = data.WXGZLocalMaterial.LocalId;
            pblog.MaterialId = data.WXGZLocalMaterial.MaterialId;
            pblog.StockNumber = data.WXGZLocalMaterial.Nums;
            pblog.CreatorId = _operator.UserId;
            pblog.CreatorName = userdata.RealName;
            pblog.OperatorId = _operator.UserId;
            pblog.Type = 1;
            pblog.OrderID = orderdetailid;
            pblog.CreateTime = DateTime.Now;
            pblog.State = 1;
            pblog.JobId = "";
            await Db.InsertAsync<PB_StockLog>(pblog);

            //维修改制领料记录
            PB_ReformMaterialReceive ReformMaterial = new PB_ReformMaterialReceive();
            ReformMaterial.Id = IdHelper.GetId();
            ReformMaterial.MaterialId = data.WXGZLocalMaterial.MaterialId;
            ReformMaterial.OrderId = ProductionOrderDetail.ParentId;
            ReformMaterial.OrderDetailId = orderdetailid;
            ReformMaterial.Nums = data.WXGZLocalMaterial.Nums;
            ReformMaterial.CollectionTime = DateTime.Now;
            ReformMaterial.CollectionUserId = _operator.UserId;
            ReformMaterial.StorId = locadata.StorId;
            ReformMaterial.LocalId = data.WXGZLocalMaterial.LocalId;
            ReformMaterial.Remarks = "";
            ReformMaterial.CreatorId = _operator.UserId;
            ReformMaterial.CreateTime = DateTime.Now;
            ReformMaterial.Deleted = false;
            await Db.InsertAsync<PB_ReformMaterialReceive>(ReformMaterial);

        }

        /// <summary>
        /// 获取维修改制领料记录
        /// </summary>
        /// <param name="OrderDetailQrCode">任务单明细二维码</param>
        /// <returns></returns>
        public async Task<List<ReformMaterialReceiveDTO>> GetReformMaterialReceiveListAsync(string OrderDetailQrCode)
        {
            //获取任务单明细Id
            string orderdetailid = OrderDetailQrCode.Split(',')?[2].ToString();

            Expression<Func<PB_ReformMaterialReceive, PB_Material, View_StorAreaRackLocation, ReformMaterialReceiveDTO>> select = (a, b, c) => new ReformMaterialReceiveDTO
            {
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                StorAreaName = c.StorAreaName
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ReformMaterialReceive>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<View_StorAreaRackLocation>() on a.LocalId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            return await q.Where(x => x.OrderDetailId == orderdetailid).ToListAsync();

        }

        /// <summary>
        /// 维修改制领料提交(生产出库单)
        /// </summary>
        /// <param name="OrderDetailQrCode">任务单明细二维码</param>
        /// <returns></returns>
        public async Task SubmitReformMaterialReceiveAsync(string OrderDetailQrCode)
        {
            //获取任务单明细Id
            string orderdetailid = OrderDetailQrCode.Split(',')?[2].ToString();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //获取领料记录
            Expression<Func<PB_ReformMaterialReceive, PB_Material, View_StorAreaRackLocation, ReformMaterialReceiveDTO>> select = (a, b, c) => new ReformMaterialReceiveDTO
            {
                MaterialName = b.Name,
                MaterialCode = b.Code,
                MaterialSpec = b.Spec,
                StorAreaName = c.StorAreaName,
                Price = b.Price
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ReformMaterialReceive>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<View_StorAreaRackLocation>() on a.LocalId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            List<ReformMaterialReceiveDTO> ReformMaterialReceivelist = await q.Where(x => x.OrderDetailId == orderdetailid).ToListAsync();

            var reformdata = ReformMaterialReceivelist.GroupBy(x => new { x.StorId, x.LocalId, x.MaterialId, x.OrderId, x.OrderDetailId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, OrderId = x.Key.OrderId, OrderDetailId = x.Key.OrderDetailId, Price = x.Key.Price, Nums = x.Sum(i => i.Nums) }).ToList();

            //出库单Id
            string outId = IdHelper.GetId();

            List<TD_OutStorDetail> OutStorDetail = new List<TD_OutStorDetail>();

            List<TD_OutStorRecord> OutStorRecord = new List<TD_OutStorRecord>();

            List<TD_OutStorage> OutStorage = new List<TD_OutStorage>();

            double? doutnums = 0;

            double? dTotalAmt = 0;

            foreach (var item in reformdata)
            {
                //出库单明细
                TD_OutStorDetail outdetail = new TD_OutStorDetail();
                outdetail.Id = IdHelper.GetId();
                outdetail.StorId = item.StorId;
                outdetail.OutStorId = outId;
                outdetail.LocalId = item.LocalId;
                outdetail.MaterialId = item.MaterialId;
                outdetail.Price = Convert.ToDouble(item.Price);
                outdetail.TotalAmt = Convert.ToDouble(item.Price * item.Nums);
                outdetail.OutNum = Convert.ToDouble(item.Nums);
                outdetail.CreateTime = DateTime.Now;
                outdetail.CreatorId = _operator.UserId;
                outdetail.Deleted = false;
                outdetail.OldOrNew = 0;
                OutStorDetail.Add(outdetail);

                //出库单明细汇总
                TD_OutStorRecord outrecord = new TD_OutStorRecord();
                outrecord.Id = IdHelper.GetId();
                outrecord.StorId = item.StorId;
                outrecord.OutStorId = outId;
                outrecord.MaterialId = item.MaterialId;
                outrecord.Price = Convert.ToDouble(item.Price);
                outrecord.TotalAmt = Convert.ToDouble(item.Price * item.Nums);
                outrecord.OutNum = Convert.ToDouble(item.Nums);
                outrecord.CreateTime = DateTime.Now;
                outrecord.CreatorId = _operator.UserId;
                outrecord.Deleted = false;
                OutStorRecord.Add(outrecord);

                doutnums += item.Nums;

                dTotalAmt += Convert.ToDouble(item.Price * item.Nums);
            }

            //根据领料获取仓库
            var stordata = ReformMaterialReceivelist.GroupBy(x => new { x.StorId }).Select(x => new { StorId = x.Key.StorId }).FirstOrDefault();

            //出库单
            TD_OutStorage Storage = new TD_OutStorage();
            Storage.Id = outId;
            Storage.StorageId = stordata.StorId;
            Storage.Code = GetTimeStamp();
            Storage.OutTime = DateTime.Now;
            Storage.OutType = "Maintainice";
            Storage.RefCode = orderdetailid;
            Storage.OutNum = doutnums;
            Storage.TotalAmt = dTotalAmt;
            Storage.Status = 0;
            Storage.Remarks = "维修改制领料出库";
            Storage.CreateTime = DateTime.Now;
            Storage.CreatorId = _operator.UserId;
            Storage.Deleted = false;
            Storage.QrCode = h_OutStorage + "," + outId;
            Storage.DepId = userdata.DepartmentId;
            Storage.ProjectId = "";
            Storage.DesignId = "";
            Storage.FactoryId = userdata.FactoryId;
            OutStorage.Add(Storage);

            await Db.InsertAsync<TD_OutStorDetail>(OutStorDetail);

            await Db.InsertAsync<TD_OutStorRecord>(OutStorRecord);

            await Db.InsertAsync<TD_OutStorage>(OutStorage);

        }

        /// <summary>
        /// 维修改制领料移除
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteReformMaterialReceiveAsync(ReformMaterialReceiveDTO data)
        {
            string sqlMain = string.Empty;
            //查询库存汇总表信息
            IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == data.MaterialId && x.LocalId == data.LocalId).FirstOrDefaultAsync();
            List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();
            if (LocalMaterial != null)
            {
                sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + data.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where MaterialId='" + data.MaterialId + "' and LocalId='" + data.LocalId + "'; ";
            }
            else
            {
                IT_LocalMaterial LocalMaterialData = new IT_LocalMaterial();
                LocalMaterialData.Id = IdHelper.GetId();
                LocalMaterialData.MaterialId = data.MaterialId;
                LocalMaterialData.StorId = data.StorId;
                LocalMaterialData.LocalId = data.LocalId;
                LocalMaterialData.Nums_N = 0;
                LocalMaterialData.Nums_O = Convert.ToDouble(data.Nums);
                LocalMaterialData.Nums_R = 0;
                LocalMaterialData.CreatorId = _operator.UserId;
                LocalMaterialData.CreateTime = DateTime.Now;
                LocalMaterialData.Deleted = false;
                LocalMaterialData.ScanNum = Convert.ToDouble(data.Nums);
                LocalMaterialData.CheckNum = 0;
                LocalMaterialList.Add(LocalMaterialData);
            }
            //获取物料信息
            PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == data.MaterialId).FirstOrDefaultAsync();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //添加库存明细
            IT_LocalDetail LocalDetail = new IT_LocalDetail();
            LocalDetail.Id = IdHelper.GetId();
            LocalDetail.StorId = data.StorId;
            LocalDetail.LocalId = data.LocalId;
            LocalDetail.MaterialId = data.MaterialId;
            LocalDetail.MeasureId = Material.storageId;
            LocalDetail.BarCode = h_Material + "," + data.MaterialId;
            LocalDetail.InTime = DateTime.Now;
            LocalDetail.Amount = Material.Price * data.Nums;
            LocalDetail.CreateTime = DateTime.Now;
            LocalDetail.CreatorId = _operator.UserId;
            LocalDetail.Price = data.Price;
            LocalDetail.Deleted = false;
            LocalDetail.Num = data.Nums;
            LocalDetail.PackId = "";
            LocalDetail.OldOrNew = 0;
            LocalDetail.RecId = "";
            LocalDetail.JobId = "";

            PB_StockLog log = new PB_StockLog();
            log.Id = IdHelper.GetId();
            log.PackId = "";
            log.MaterialId = data.MaterialId;
            log.StorId = data.StorId;
            log.LocationId = data.LocalId;
            log.StockNumber = data.Nums;
            log.CreatorId = _operator.UserId;
            log.Deleted = false;
            log.CreatorName = userdata.RealName;
            log.OperatorId = _operator.UserId;
            log.Type = 1;
            log.OrderID = data.OrderDetailId;
            log.CreateTime = DateTime.Now;
            log.State = 0;
            log.OldOrNew = 0;
            log.CirBillId = "";
            log.JobId = "";

            sqlMain += " delete from PB_ReformMaterialReceive where Id='" + data.Id + "'; ";
            sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+" + data.Nums + " where Id='" + data.MaterialId + "'; ";

            await Db.InsertAsync<IT_LocalDetail>(LocalDetail);

            await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);

            await Db.InsertAsync<PB_StockLog>(log);

            await Db.ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 扫描任务单明细二维码获取任务单明细信息
        /// </summary>
        /// <param name="OrderDetailQrCode">任务单明细二维码</param>
        /// <returns></returns>
        public async Task<PB_ProductionOrderDetail> GetProductionOrderDetailDataAsync(string OrderDetailQrCode)
        {
            string[] model = OrderDetailQrCode.Split(',');
            string orderdetailId = string.Empty;
            if (model.Length == 3)
            {
                orderdetailId = model?[2].ToString();
            }
            else
            {
                orderdetailId = model?[1].ToString();
            }
            TD_OutStorage OutStorage = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == orderdetailId).FirstOrDefaultAsync();
            if (OutStorage != null)
            {
                throw new BusException("不能重复领料");
            }
            PB_ProductionOrderDetail OrderDetail = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == orderdetailId).FirstOrDefaultAsync();
            if (OrderDetail != null)
            {
                PB_ProductionOrder Order = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == OrderDetail.ParentId && x.IsRefurbishment == 3).FirstOrDefaultAsync();
                if (Order.IsNullOrEmpty())
                {
                    throw new BusException("请扫描维修改制类型的任务单信息");
                } 
            }
            return OrderDetail;
        }

        #endregion

        #endregion

        #region  打印服务

        /// <summary>
        /// 校验组织编码,并返回组织信息和打印机信息
        /// </summary>
        /// <param name="DeptCode">组织编码</param>
        /// <returns></returns>
        public async Task<DepartmentPrintDTO> GetDepartmentDataAsync(string DeptCode)
        {
            if (DeptCode.IsNullOrEmpty())
            {
                throw new BusException("请输入正确的组织编码");
            }
            //根据组织编码获取组织信息
            Base_Department deptdata = await Db.GetIQueryable<Base_Department>().Where(x => x.DeptCode == DeptCode).FirstOrDefaultAsync();
            if (deptdata == null)
            {
                throw new BusException("请输入正确的组织编码");
            }
            else
            {
                string deptId = string.Empty;
                if (deptdata.Type != 8)
                {
                    if (deptdata.Type == 1)
                    {
                        deptId = deptdata.Id;
                    }
                    else
                    {
                        if (deptId.IsNullOrEmpty())
                        {
                            string parentId = deptdata.ParentId;
                            do
                            {
                                var data = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == parentId).FirstOrDefaultAsync();
                                if (data.Type != 1)
                                {
                                    parentId = data.ParentId;
                                }
                                else
                                {
                                    deptId = data.Id;
                                }
                            } while (deptId == "");
                        }
                    }
                    deptdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == deptId).FirstOrDefaultAsync();
                }
                DepartmentPrintDTO printdata = new DepartmentPrintDTO();
                printdata.DeptId = deptdata.Id;
                printdata.DeptCode = deptdata.DeptCode;
                printdata.DeptName = deptdata.Name;
                List<PB_Printer> listdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.DeptId == deptdata.Id).ToListAsync();
                printdata.PrinterList = listdata;
                return printdata;
            }
        }

        public async Task<List<WorkReportingDto>> ViewWorkReportingDto(string month)
        {
            #region 数据库列转行
            //List<WorkReportingDto> LIST = new List<WorkReportingDto>();
            //int Year = Convert.ToInt32(month.Split('-')[0].ToString());
            //int Month = Convert.ToInt32(month.Split('-')[1].ToString());
            //StringBuilder sql = new StringBuilder();
            ////获取指定月份天数
            //int days = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetDaysInMonth(Year, Month);
            //int thisDays = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetDaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
            //sql.AppendLine("SELECT");
            //sql.AppendLine(" ReportUserId,");
            //sql.AppendLine(" ReportUserName,");
            //sql.AppendLine(" MaterId,");
            //sql.AppendLine(" MaterName,");
            //sql.AppendLine(" Name,");
            //string sqlmain = "";
            //if (month.IsNullOrEmpty())
            //{
            //    for (int VALUE = 1; VALUE <= days; VALUE++)
            //    {
            //        sqlmain += $" 	CONCAT(IFNULL( sum( CASE WHEN ReportTime = '{DateTime.Now.Year}-{DateTime.Now.Month}-{VALUE}' THEN Nums END ), 0 ),',',IFNULL( sum( CASE WHEN ReportTime = '{DateTime.Now.Year}-{DateTime.Now.Month}-{VALUE}' THEN QualityNums END ), 0 )) as DAY{VALUE},";
            //    }
            //    sql.AppendLine(sqlmain);
            //}
            //else
            //{
            //    for (int VALUE = 1; VALUE <= thisDays; VALUE++)
            //    {
            //        sqlmain += $" 	CONCAT(IFNULL( sum( CASE WHEN ReportTime = '{DateTime.Now.Year}-{DateTime.Now.Month}-{VALUE}' THEN Nums END ), 0 ),',',IFNULL( sum( CASE WHEN ReportTime = '{DateTime.Now.Year}-{DateTime.Now.Month}-{VALUE}' THEN QualityNums END ), 0 )) as DAY{VALUE},";
            //    }
            //    sql.AppendLine(sqlmain);
            //}
            //sql.AppendLine("ifnull(sum(Nums), 0) AS Subtotal,");
            //sql.AppendLine("ifnull( sum( QualityNums ), 0 ) AS StatisticalQuantity ");
            //sql.AppendLine("FROM");
            //sql.AppendLine("v_JobBooking");
            //if (!month.IsNullOrEmpty())
            //{
            //    sql.AppendLine($"WHERE YEAR(ReportTime) = '{Year}' AND MONTH(ReportTime) = '{Month}'");
            //}
            //else
            //{
            //    sql.AppendLine($"WHERE YEAR(ReportTime) =YEAR(NOW()) AND MONTH(ReportTime) = MONTH(NOW())");
            //}
            //sql.AppendLine("GROUP BY");
            //sql.AppendLine("ReportUserId,");
            //sql.AppendLine("MaterId,");
            //sql.AppendLine(" ReportUserName,");
            //sql.AppendLine("MaterName,");
            //sql.AppendLine(" Name");
            //LIST = await Db.GetListBySqlAsync<WorkReportingDto>(sql.ToString());
            ////int pagecount;//总页数
            ////List<WorkReportingDto> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            ////List<WorkReportingDto> productes = new List<WorkReportingDto>();//用来存储要展示的数据
            ////int pagees = listpro_down.Count;//所有数据的总条数
            ////                                //计算总页数
            ////if (pagees % input.PageRows == 0)
            ////{
            ////    pagecount = pagees / input.PageRows;
            ////}
            ////else
            ////{
            ////    pagecount = (pagees / input.PageRows) + 1;
            ////}
            ////productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            //return LIST;
            #endregion

            #region 程序列转行
            //获取基础数据
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("DATE(ReportTime) ReportTime,");
            sql.Append("ReportUserId,");
            sql.Append("ReportUserName,");
            sql.Append("MaterId,");
            sql.Append("MaterName,");
            sql.Append("Name,");
            sql.Append("ifnull(sum(Nums), 0) AS Subtotal,");
            sql.Append("ifnull( sum( QualityNums ), 0 ) AS StatisticalQuantity ");
            sql.Append("FROM ");
            sql.Append("v_JobBooking ");
            sql.Append("WHERE ");
            sql.Append("date_format(ReportTime, '%Y-%m' )='" + month + "' ");
            sql.Append("GROUP BY ");
            sql.Append("ReportUserId,");
            sql.Append("MaterId,");
            sql.Append("ReportUserName,");
            sql.Append("MaterName,");
            sql.Append("Name,");
            sql.Append("DATE(ReportTime)");
            var baseList = await Db.GetListBySqlAsync<v_JobBooking>(sql.ToString());
            //获取所有工人ID
            var usrList = baseList.Select(s => s.ReportUserId).Distinct();
            //填充MODEL（列转行）
            List<WorkReportingDto> result = new List<WorkReportingDto>();
            foreach (var usr in usrList)
            {
                //筛选本轮工人的数据
                var tmpList = baseList.Where(s => s.ReportUserId == usr).ToList();
                WorkReportingDto tmp = new WorkReportingDto();
                tmp.MaterName = tmpList[0].MaterName;
                tmp.Name = tmpList[0].Name;
                tmp.ReportUserId = tmpList[0].ReportUserId;
                tmp.ReportUserName = tmpList[0].ReportUserName;
                double _total = 0;
                double _stat = 0;
                for (int day = 1; day < 32; day++)
                {
                    string dayStr = "";
                    if (day < 10)
                    {
                        dayStr = "0" + day;
                    }
                    else {
                        dayStr = day.ToString();
                    }
                    var entity = tmpList.FirstOrDefault(s => Convert.ToDateTime(s.ReportTime).ToString("yyyy-MM-dd").Equals(month + "-" + dayStr));
                    //累加报工数和质检数
                    if (!entity.IsNullOrEmpty())
                    {
                        _total += Convert.ToDouble(entity.Subtotal);
                        _stat += Convert.ToDouble(entity.StatisticalQuantity);
                    }
                    #region 根据日赋值
                    switch (day)
                    {
                        case 1:
                            tmp.Day1 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day1 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 2:
                            tmp.Day2 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day2 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 3:
                            tmp.Day3 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day3 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 4:
                            tmp.Day4 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day4 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 5:
                            tmp.Day5 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day5 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 6:
                            tmp.Day6 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day6 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 7:
                            tmp.Day7 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day7 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 8:
                            tmp.Day8 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day8 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 9:
                            tmp.Day9 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day9 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 10:
                            tmp.Day10 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day10 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 11:
                            tmp.Day11 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day11 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 12:
                            tmp.Day12 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day12 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 13:
                            tmp.Day13 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day13 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 14:
                            tmp.Day14 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day14 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 15:
                            tmp.Day15 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day15 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 16:
                            tmp.Day16 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day16 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 17:
                            tmp.Day17 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day17 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 18:
                            tmp.Day18 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day18 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 19:
                            tmp.Day19 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day19 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 20:
                            tmp.Day20 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day20 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 21:
                            tmp.Day21 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day21 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 22:
                            tmp.Day22 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day22 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 23:
                            tmp.Day23 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day23 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 24:
                            tmp.Day24 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day24 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 25:
                            tmp.Day25 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day25 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 26:
                            tmp.Day26 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day26 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 27:
                            tmp.Day27 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day27 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 28:
                            tmp.Day28 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day28 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 29:
                            tmp.Day29 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day29 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 30:
                            tmp.Day30 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day30 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                        case 31:
                            tmp.Day31 = "0.0000,0.0000";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.Day31 = Convert.ToDouble(entity.Subtotal).ToString("0.0000") + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                            }
                            break;
                    }
                    #endregion
                }
                tmp.Subtotal = _total.ToString();
                tmp.StatisticalQuantity = _stat.ToString();
                result.Add(tmp);
            }
            return result;
            #endregion
        }
        /// <summary>
        /// PC快速质检
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task UpdataRapidInspection(QuickWorkReportData Data)
        {

            string[] usermodel =Data.UserCode.Split(',');
            if (Data.flag == 0)
            {
                
               string sqlMain = @"update PB_CirculationBill set QualityUserId='" + _operator.UserId + "',QualityTime=NOW(),QualityNums='" + Data.ReturnNums + "' where Id='" + Data.Id + "'";
                 await ExecuteSqlAsync(sqlMain);
            }
            else {
              
                
                        string sqlMain = @"update PB_CirculationBill set Statistician='" + _operator.UserId + "',StatisticalTime=NOW(),StatisticalQuantity='" + Data.StatisticsNums + "' where Id='" + Data.Id + "'";
                        await ExecuteSqlAsync(sqlMain);
                  
                }
          
               

        }

        public async Task<List<ReportStatistics>> GetReportStatistics(string month)
        {
            List<ReportStatistics> reportStatistics = new List<ReportStatistics>();
            StringBuilder sql = new StringBuilder();
            //获取报工人
            sql.AppendLine("SELECT  ");
            sql.AppendLine(" * "); 
            sql.AppendLine("FROM ");
            sql.AppendLine(" ( ");
            sql.AppendLine("SELECT ");
            sql.AppendLine("date_format(a.ReportTime, '%Y-%m') ReportTime, ");
            sql.AppendLine("b.Id, ");
            sql.AppendLine("b.RealName, ");
            sql.AppendLine("IFNULL(SUM(a.StatisticsNums), 0) StatisticsNums ");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_JobBooking AS a");
            sql.AppendLine("LEFT JOIN Base_User AS b ON a.ReportUserId = b.Id ");
            sql.AppendLine("WHERE ");
            sql.AppendLine("date_format(a.ReportTime, '%Y-%m') = '"+ month + "' ");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("b.Id, ");
            sql.AppendLine("b.RealName, ");
            sql.AppendLine("date_format(a.ReportTime, '%Y-%m') UNION ALL ");
            sql.AppendLine("SELECT");
            sql.AppendLine("date_format(a.SendTime, '%Y-%m') ReportTime, ");
            sql.AppendLine("b.Id, ");
            sql.AppendLine("b.RealName, ");
            sql.AppendLine("IFNULL(SUM(a.StatisticalQuantity), 0) StatisticsNums ");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_CirculationBill AS a ");
            sql.AppendLine("LEFT JOIN Base_User AS b ON a.WorkerId = b.Id ");
            if (!month.IsNullOrEmpty()) {
            sql.AppendLine("WHERE date_format(a.SendTime, '%Y-%m') = '" + month + "' ");
            }
            sql.AppendLine("GROUP BY ");
            sql.AppendLine("b.Id, ");
            sql.AppendLine("b.RealName, ");
            sql.AppendLine("date_format(a.SendTime, '%Y-%m') ");
            sql.AppendLine(" ) AS T ");
            reportStatistics =await Db.GetListBySqlAsync<ReportStatistics>(sql.ToString());

            return reportStatistics;
        }


        /// <summary>
        /// 通过人员id 年月获取报工物料明细
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public async Task  <List<StatisticalDetails>> GetWorkReportingList(string UserId, string month)
        {
            #region 数据库列转行
          
            #endregion

            #region 程序列转行
            //获取基础数据
            StringBuilder sql = new StringBuilder();
        
            sql.AppendLine("SELECT   ");
            sql.AppendLine("`Sub`.`Id` AS `Id`,   ");
            sql.AppendLine("`Sub`.`Name` AS `Name`,   ");
            sql.AppendLine("`PB_JobBooking`.`ReportUserId` AS `ReportUserId`,   ");
            sql.AppendLine("`PB_JobBooking`.`ReportUserName` AS `ReportUserName`,   ");
            sql.AppendLine("ifnull(sum( `PB_JobBooking`.`Nums` ), 0) AS `Nums`,   ");
            sql.AppendLine("ifnull(sum( `PB_JobBooking`.`StatisticsNums` ), 0) AS `StatisticalQuantity`,   ");
            sql.AppendLine("cast( `PB_JobBooking`.`ReportTime` AS date) AS `ReportTime`,   ");
            sql.AppendLine("`Mater`.`Id` AS `MaterId`,   ");
            sql.AppendLine("`Mater`.`Name` AS `MaterName`,   ");
            sql.AppendLine("`Mater`.`Name` AS `SubordinateProductName`  ,  ");
            sql.AppendLine("`Mater`.`Id` AS `SubordinateProduct` 	");
            sql.AppendLine("FROM   ");
            sql.AppendLine("`PB_JobBooking`   ");
            sql.AppendLine(" LEFT JOIN `Base_Device` ON   ");
            sql.AppendLine("`PB_JobBooking`.`DeviceId` = `Base_Device`.`Id`    ");
            sql.AppendLine("LEFT JOIN `PB_ProcecureSub` `Sub` ON   ");
            sql.AppendLine("`Base_Device`.`ProcecureSubId` = `Sub`.`Id`    ");
            sql.AppendLine("LEFT JOIN `PB_Material` `Mater` ON   `PB_JobBooking`.`MaterialId` = `Mater`.`Id` ");
            sql.AppendLine("WHERE `PB_JobBooking`.`ReportUserId`= '" + UserId+"' ");
            if (!month.IsNullOrEmpty()) {
                sql.AppendLine("and date_format(`PB_JobBooking`.`ReportTime`, '%Y-%m') = '"+month+"'"); 
            }
            sql.AppendLine("GROUP BY");
            sql.AppendLine("`PB_JobBooking`.`ReportUserId`,");
            sql.AppendLine("`PB_JobBooking`.`ReportUserName`,");
            sql.AppendLine("`Sub`.`Id`,");
            sql.AppendLine("`Sub`.`Name`,");
            sql.AppendLine("`Mater`.`Id`,");
            sql.AppendLine(" DATE(PB_JobBooking.ReportTime) UNION ALL");
            sql.AppendLine("SELECT");
            sql.AppendLine("`Sub`.`Id` AS `Id`,");
            sql.AppendLine("`Sub`.`Name` AS `Name`,");
            sql.AppendLine("`bill`.`WorkerId` AS `ReportUserId`,");
            sql.AppendLine("`users`.`RealName` AS `ReportUserName`,");
            sql.AppendLine(" ifnull(sum( `bill`.`WorkReportQuantity` ), 0) AS `Nums`,");
            sql.AppendLine(" ifnull(sum( `bill`.`StatisticalQuantity` ), 0) AS `StatisticalQuantity`,");
            sql.AppendLine("cast( `bill`.`SendTime` AS date) AS `ReportTime`,");
            sql.AppendLine("`Mater`.`Id` AS `MaterId`,");
            sql.AppendLine("`Mater`.`Name` AS `MaterName`,");
            sql.AppendLine("`Maters`.`Name` AS `SubordinateProductName`, 	");
            sql.AppendLine("`Maters`.`Id` AS `SubordinateProduct` 	");
            sql.AppendLine("FROM");
            sql.AppendLine("`PB_CirculationBill` `bill`");
            sql.AppendLine("LEFT JOIN `Base_User` `users` ON");
            sql.AppendLine("`bill`.`WorkerId` = `users`.`Id` ");
            sql.AppendLine("LEFT JOIN `Base_Device` ON");
            sql.AppendLine("`bill`.`DeviceId` = `Base_Device`.`Id` ");
            sql.AppendLine("LEFT JOIN `PB_ProcecureSub` `Sub` ON");
            sql.AppendLine("`Base_Device`.`ProcecureSubId` = `Sub`.`Id` ");
            sql.AppendLine(" LEFT JOIN `PB_Material` `Mater` ON");
            sql.AppendLine("`bill`.`MaterialId` = `Mater`.`Id` ");
            sql.AppendLine("  LEFT JOIN `PB_Material` `Maters` ON");
            sql.AppendLine("	`bill`.`SubordinateProduct` = `Maters`.`Id` ");
            sql.AppendLine(" WHERE `bill`.`WorkerId` = '" + UserId+"'");
            if (!month.IsNullOrEmpty()) {
                sql.AppendLine(" and  date_format(`bill`.`SendTime`, '%Y-%m') = '"+month+"'");
            }
            sql.AppendLine("GROUP BY");
            sql.AppendLine("`bill`.`WorkerId`,");
            sql.AppendLine("`users`.`RealName`,");
            sql.AppendLine("`Sub`.`Id`,");
            sql.AppendLine("`Sub`.`Name`,");
            sql.AppendLine("`Mater`.`Id`,");
            sql.AppendLine("`Maters`.`Name`,");
            sql.AppendLine("`Maters`.`Id`,");
            sql.AppendLine("DATE(bill.SendTime) ");
           
            var baseList = await Db.GetListBySqlAsync<v_JobBooking>(sql.ToString());
            //获取所有工人ID
            var usrList = baseList.Select(s => s.ReportUserId==UserId).Distinct();
            //填充MODEL（列转行）
            List<StatisticalDetails> result = new List<StatisticalDetails>();
            foreach (var usr in usrList)
            {
                //筛选本轮工人的数据
                var tmpList = baseList. Where(s => s.ReportUserId == UserId).ToList();
                
                for (int i=0; i<tmpList.Count; i++) {
                    StatisticalDetails tmp = new StatisticalDetails();
                    tmp.MaterName = tmpList[i].MaterName;
                    tmp.Name = tmpList[i].Name;
                    tmp.ReportTime = tmpList[i].ReportTime;
                    tmp.ReportUserId = tmpList[i].ReportUserId;
                    tmp.ReportUserName = tmpList[i].ReportUserName;
                    tmp.SubordinateProductName = tmpList[i].SubordinateProductName;
                    tmp.SubordinateProduct = tmpList[i].SubordinateProduct;
                    double _stat = 0;
                    for (int day = 1; day < 32; day++)
                    {
                        string dayStr = "";
                        if (day < 10)
                        {
                            dayStr = "0" + day;
                        }
                        else {
                            dayStr = day.ToString();
                        }

                            var entity = tmpList.FirstOrDefault(s => Convert.ToDateTime(s.ReportTime).ToString("yyyy-MM-dd").Equals(month + "-" + dayStr) &&s.MaterId== tmpList[i].MaterId&&s.SubordinateProduct== tmpList[i].SubordinateProduct);
                        //累加报工数和质检数
                        if (!entity.IsNullOrEmpty())
                        {

                            _stat += Convert.ToDouble(entity.StatisticalQuantity);
                        }
                        #region 根据日赋值
                        switch (day)
                        {
                            case 1:
                                tmp.Day1 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day1 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 2:
                                tmp.Day2 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day2 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 3:
                                tmp.Day3 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day3 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 4:
                                tmp.Day4 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day4 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 5:
                                tmp.Day5 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day5 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 6:
                                tmp.Day6 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day6 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 7:
                                tmp.Day7 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day7 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 8:
                                tmp.Day8 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day8 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 9:
                                tmp.Day9 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day9 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 10:
                                tmp.Day10 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day10 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 11:
                                tmp.Day11 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day11 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 12:
                                tmp.Day12 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day12 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 13:
                                tmp.Day13 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day13 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 14:
                                tmp.Day14 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day14 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 15:
                                tmp.Day15 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day15 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 16:
                                tmp.Day16 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day16 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 17:
                                tmp.Day17 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day17 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 18:
                                tmp.Day18 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day18 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 19:
                                tmp.Day19 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day19 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 20:
                                tmp.Day20 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day20 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 21:
                                tmp.Day21 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day21 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 22:
                                tmp.Day22 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day22 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 23:
                                tmp.Day23 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day23 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 24:
                                tmp.Day24 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day24 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 25:
                                tmp.Day25 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day25 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 26:
                                tmp.Day26 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day26 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 27:
                                tmp.Day27 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day27 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 28:
                                tmp.Day28 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day28 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 29:
                                tmp.Day29 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day29 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 30:
                                tmp.Day30 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day30 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                            case 31:
                                tmp.Day31 = "无,无,无,0.0000";
                                if (!entity.IsNullOrEmpty())
                                {
                                    tmp.Day31 = entity.SubordinateProductName + "," + entity.MaterName + "," + entity.Name + "," + Convert.ToDouble(entity.StatisticalQuantity).ToString("0.0000");
                                }
                                break;
                        }
                        #endregion
                    }

                    tmp.StatisticalQuantity = _stat.ToString();
                    result.Add(tmp);
                }
               
            }
            return result;
            #endregion

        }

        public async Task<MonthSummary> GetMonthSummary(string month)
        {
            MonthSummary monthSummary = new MonthSummary(); 
            StringBuilder sql = new StringBuilder();
            sql.AppendLine("SELECT");
            sql.AppendLine("IFNULL(SUM(pb_jobing.StatisticalQuantity), 0) StatisticalQuantity,");
            sql.AppendLine("ReportTime");
            sql.AppendLine("FROM");
            sql.AppendLine("(");
            sql.AppendLine("SELECT");
            sql.AppendLine("ifnull(sum( `PB_JobBooking`.`StatisticsNums` ), 0) AS `StatisticalQuantity`,");
            sql.AppendLine("cast( `PB_JobBooking`.`ReportTime` AS date) AS `ReportTime` ");
            sql.AppendLine("FROM");
            sql.AppendLine("`PB_JobBooking`");
            sql.AppendLine("LEFT JOIN `Base_Device` ON `PB_JobBooking`.`DeviceId` = `Base_Device`.`Id`");
            sql.AppendLine(" LEFT JOIN `PB_ProcecureSub` `Sub` ON `Base_Device`.`ProcecureSubId` = `Sub`.`Id`");
            sql.AppendLine("LEFT JOIN `PB_Material` `Mater` ON `PB_JobBooking`.`MaterialId` = `Mater`.`Id` ");
            sql.AppendLine("WHERE");
            sql.AppendLine("date_format( `PB_JobBooking`.`ReportTime`, '%Y-%m') = '"+month+"'");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("DATE(PB_JobBooking.ReportTime) UNION ALL");
            sql.AppendLine("SELECT");
            sql.AppendLine("ifnull(sum( `bill`.`StatisticalQuantity` ), 0) AS `StatisticalQuantity`,");
            sql.AppendLine("cast( `bill`.`SendTime` AS date) AS `ReportTime` ");
            sql.AppendLine("FROM");
            sql.AppendLine("`PB_CirculationBill` `bill`");
            sql.AppendLine("LEFT JOIN `Base_User` `users` ON `bill`.`WorkerId` = `users`.`Id`");
            sql.AppendLine("LEFT JOIN `Base_Device` ON `bill`.`DeviceId` = `Base_Device`.`Id`");
            sql.AppendLine("LEFT JOIN `PB_ProcecureSub` `Sub` ON `Base_Device`.`ProcecureSubId` = `Sub`.`Id`");
            sql.AppendLine("LEFT JOIN `PB_Material` `Mater` ON `bill`.`MaterialId` = `Mater`.`Id`");
            sql.AppendLine("LEFT JOIN `PB_Material` `Maters` ON `bill`.`SubordinateProduct` = `Maters`.`Id` ");
            sql.AppendLine("WHERE");
            sql.AppendLine("date_format( `bill`.`SendTime`, '%Y-%m') = '"+month+"'");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("DATE(bill.SendTime)) AS pb_jobing");
            sql.AppendLine("GROUP BY");
            sql.AppendLine("pb_jobing.ReportTime");
            sql.AppendLine("ORDER BY");
            sql.AppendLine("pb_jobing.ReportTime");
            var models =await Db.GetListBySqlAsync<SummaryDetails>(sql.ToString());
            for (int i=1;i<32;i++) {
                string days = "";
                if (i < 10)
                {
                    days = 0 + i.ToString();
                }
                else {
                    days = i.ToString();
                }
                var db = models.Where(m=> Convert.ToDateTime(m.ReportTime).ToString("yyyy-MM-dd").Equals(month + "-" + days)).FirstOrDefault();
                
                switch (i) {
                    case 1:
                        monthSummary.Day1 = "0";
                        if (db!=null) {
                            monthSummary.Day1 = db.StatisticalQuantity;
                        }
                    break;
                    case 2:
                        monthSummary.Day2 = "0";
                        if (db != null)
                        {
                            monthSummary.Day2 = db.StatisticalQuantity;
                        }
                        break;
                    case 3:
                        monthSummary.Day3 = "0";
                        if (db != null)
                        {
                            monthSummary.Day3 = db.StatisticalQuantity;
                        }
                        break;
                    case 4:
                        monthSummary.Day4 = "0";
                        if (db != null)
                        {
                            monthSummary.Day4 = db.StatisticalQuantity;
                        }
                        break;
                    case 5:
                        monthSummary.Day5 = "0";
                        if (db != null)
                        {
                            monthSummary.Day5 = db.StatisticalQuantity;
                        }
                        break;
                    case 6:
                        monthSummary.Day6 = "0";
                        if (db != null)
                        {
                            monthSummary.Day6 = db.StatisticalQuantity;
                        }
                        break;
                    case 7:
                        monthSummary.Day7 = "0";
                        if (db != null)
                        {
                            monthSummary.Day7 = db.StatisticalQuantity;
                        }
                        break;
                    case 8:
                        monthSummary.Day8 = "0";
                        if (db != null)
                        {
                            monthSummary.Day8 = db.StatisticalQuantity;
                        }
                        break;
                    case 9:
                        monthSummary.Day9 = "0";
                        if (db != null)
                        {
                            monthSummary.Day9 = db.StatisticalQuantity;
                        }
                        break;
                    case 10:
                        monthSummary.Day10 = "0";
                        if (db != null)
                        {
                            monthSummary.Day10 = db.StatisticalQuantity;
                        }
                        break;
                    case 11:
                        monthSummary.Day11 = "0";
                        if (db != null)
                        {
                            monthSummary.Day11 = db.StatisticalQuantity;
                        }
                        break;
                    case 12:
                        monthSummary.Day12 = "0";
                        if (db != null)
                        {
                            monthSummary.Day12 = db.StatisticalQuantity;
                        }
                        break;
                    case 13:
                        monthSummary.Day13 = "0";
                        if (db != null)
                        {
                            monthSummary.Day13 = db.StatisticalQuantity;
                        }
                        break;
                    case 14:
                        monthSummary.Day14 = "0";
                        if (db != null)
                        {
                            monthSummary.Day14 = db.StatisticalQuantity;
                        }
                        break;
                    case 15:
                        monthSummary.Day15 = "0";
                        if (db != null)
                        {
                            monthSummary.Day15 = db.StatisticalQuantity;
                        }
                        break;
                    case 16:
                        monthSummary.Day16 = "0";
                        if (db != null)
                        {
                            monthSummary.Day16 = db.StatisticalQuantity;
                        }
                        break;
                    case 17:
                        monthSummary.Day17 = "0";
                        if (db != null)
                        {
                            monthSummary.Day17 = db.StatisticalQuantity;
                        }
                        break;
                    case 18:
                        monthSummary.Day18 = "0";
                        if (db != null)
                        {
                            monthSummary.Day18 = db.StatisticalQuantity;
                        }
                        break;

                    case 19:
                        monthSummary.Day19 = "0";
                        if (db != null)
                        {
                            monthSummary.Day19 = db.StatisticalQuantity;
                        }
                        break;
                    case 20:
                        monthSummary.Day20 = "0";
                        if (db != null)
                        {
                            monthSummary.Day20 = db.StatisticalQuantity;
                        }
                        break;
                    case 21:
                        monthSummary.Day21 = "0";
                        if (db != null)
                        {
                            monthSummary.Day21 = db.StatisticalQuantity;
                        }
                        break;

                    case 22:
                        monthSummary.Day22 = "0";
                        if (db != null)
                        {
                            monthSummary.Day22 = db.StatisticalQuantity;
                        }
                        break;

                    case 23:
                        monthSummary.Day23 = "0";
                        if (db != null)
                        {
                            monthSummary.Day23 = db.StatisticalQuantity;
                        }
                        break;

                    case 24:
                        monthSummary.Day24 = "0";
                        if (db != null)
                        {
                            monthSummary.Day24 = db.StatisticalQuantity;
                        }
                        break;

                    case 25:
                        monthSummary.Day25 = "0";
                        if (db != null)
                        {
                            monthSummary.Day25 = db.StatisticalQuantity;
                        }
                        break;

                    case 26:
                        monthSummary.Day26 = "0";
                        if (db != null)
                        {
                            monthSummary.Day26 = db.StatisticalQuantity;
                        }
                        break;
                    case 27:
                        monthSummary.Day27 = "0";
                        if (db != null)
                        {
                            monthSummary.Day27= db.StatisticalQuantity;
                        }
                        break;
                    case 28:
                        monthSummary.Day28 = "0";
                        if (db != null)
                        {
                            monthSummary.Day28 = db.StatisticalQuantity;
                        }
                        break;
                    case 29:
                        monthSummary.Day29= "0";
                        if (db != null)
                        {
                            monthSummary.Day29 = db.StatisticalQuantity;
                        }
                        break;
                    case 30:
                        monthSummary.Day30= "0";
                        if (db != null)
                        {
                            monthSummary.Day30= db.StatisticalQuantity;
                        }
                        break;
                    case 31:
                        monthSummary.Day31 = "0";
                        if (db != null)
                        {
                            monthSummary.Day31= db.StatisticalQuantity;
                        }
                        break;






                }
            }
            return monthSummary;
        }

        #endregion

        #region 私有成员

        #endregion
    }
}